├── .gitignore
├── .travis.yml
├── LICENSE
├── Makefile
├── README.md
├── ebin
└── rec2json.app
├── erlang.mk
├── rebar.config
├── src
├── r2j_compile.erl
├── r2j_type.erl
└── rec2json.erl
└── test
├── careful_tests.erl
├── default_property.erl
├── default_value_tests.erl
├── prop_test_rec.erl
├── prop_test_rec.hrl
├── prop_test_rec_inner.erl
├── prop_test_rec_inner.hrl
├── r2j_compile_tests.erl
├── r2j_compile_tests.hrl
├── r2j_type_tests.erl
├── rec2json_tests.erl
├── renamed_property.erl
├── suppress_property.erl
├── test_person.erl
├── test_rec.erl
└── test_rec.hrl
/.gitignore:
--------------------------------------------------------------------------------
1 | deps
2 | ebin
3 | logs
4 | *.swp
5 | *.swo
6 | .eunit
7 | test/*.beam
8 | .local_dialyzer_plt
9 | .erlang.mk
10 | rec2json.d
11 | .rec2json.plt
12 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: erlang
2 | otp_release:
3 | - 21.0
4 | - 20.0
5 | - 19.0
6 |
7 | script: make tests
8 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License, Version 2.0
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
13 |
14 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
15 |
16 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
17 |
18 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
19 |
20 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
21 |
22 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
23 |
24 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
25 |
26 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
27 |
28 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
29 |
30 | 2. Grant of Copyright License.
31 |
32 | Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
33 |
34 | 3. Grant of Patent License.
35 |
36 | Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
37 |
38 | 4. Redistribution.
39 |
40 | You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
41 |
42 | You must give any other recipients of the Work or Derivative Works a copy of this License; and
43 | You must cause any modified files to carry prominent notices stating that You changed the files; and
44 | You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
45 | If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
46 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
47 |
48 | 5. Submission of Contributions.
49 |
50 | Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
51 |
52 | 6. Trademarks.
53 |
54 | This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
55 |
56 | 7. Disclaimer of Warranty.
57 |
58 | Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
59 |
60 | 8. Limitation of Liability.
61 |
62 | In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
63 |
64 | 9. Accepting Warranty or Additional Liability.
65 |
66 | While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
67 |
68 | END OF TERMS AND CONDITIONS
69 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | PROJECT = rec2json
2 | PROJECT_DESCRIPTION = Compile erlang record definitions into modules to convert them to/from json easily.
3 | PROJECT_VERSION = 4.0.1
4 |
5 | TEST_DEPS = proper jsx
6 | dep_proper = git https://github.com/manopapad/proper master
7 | dep_jsx = git https://github.com/talentdeficit/jsx v2.4.0
8 |
9 | app:: rebar.config
10 |
11 | include erlang.mk
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # rec2json
2 | [](https://travis-ci.org/lordnull/rec2json)
3 |
4 | ## Overview
5 |
6 | Rec2json is a parse transform that takes a module which defines a record of
7 | the same name and adds to_json, from_json, and introspection functions. The
8 | to_json and from_json convert to and from the map based format used by jsx and
9 | other json encoding and decoding libraries.
10 |
11 | ## Features
12 |
13 | * Uses a parse transform.
14 | * Type checking on json -> record conversion using primitive built-in types.
15 | * Type checking can be extended to include user defined types.
16 | * Atom 'undefined' fields in records optionally skipped or set to null.
17 | * Atom 'null' in json optionally converted to 'undefined'.
18 | * Post processing options on record -> json convertion.
19 | * Seed json -> record conversion with a record.
20 | * Nested json -> record and record -> json conversions for other records
21 | that have been compiled using rec2json.
22 | * Generated module has accessor functions for fields and field_names for
23 | list of fields in the record.
24 | * Above feature can be surpressed, and is careful by default.
25 | * Generated module exports functions to examine structure and types for a
26 | record.
27 |
28 | ## Compiling
29 |
30 | make
31 |
32 | To run tests:
33 |
34 | make tests
35 |
36 | make check
37 |
38 | ## Use
39 |
40 | The rec2json parse_transform looks for a record with the same name as the
41 | module. It doesn't matter whether the record was defined directly in the
42 | module or in an include file.
43 |
44 | -compile([{parse_transform, rec2json}]).
45 |
46 | The transformed modules depend on the rec2json application's modules.
47 |
48 | The records are unchanged and can be used normally.
49 |
50 | Options are passed to the rec2json parse transform through compile options.
51 | The parse transform checks for the key 'rec2json' in the compile options.
52 | The value is expected to be a proplist.
53 |
54 | Options can also be passed in on a per-module basis by adding one or more
55 | `rec2json` module attributes. A `rec2json` module attribute can either be a
56 | tuple for one option, or a list of option tuples. They all get mashed together.
57 | Using the same option more than once has undefined behavior.
58 |
59 | Options are:
60 |
61 |
62 |
63 | Option | Default: Values | Description |
64 |
65 |
66 | generate_accessors | true : boolean() | If set to
67 | true, functions for accessing the fields of a record are exported and
68 | created. If set to false, they are not created nor exported. |
69 |
70 |
71 | generate_setters | true : boolean() | If set to
72 | true, functions for setting the fields of a record are created and
73 | exported. These are of the form Field(NewVal, Record). If set to false, they
74 | are not created nor exported.
75 | |
76 |
77 |
78 | careful | true : boolean() | If set to true,
79 | rec2json's parse transform avoids altering or adding functions that are
80 | already defined in the module. This means you can override the default
81 | to_json/1 function to call to_json/2 with a specific set of options. |
82 |
83 |
84 | generate_type | true : boolean() | If set to
85 | true, a type is generated for the record, and that type is exported. In
86 | addition, a function is generated so that other rec2json records using the
87 | exported type work as expected. |
88 |
89 |
90 | type_name | ?MODULE : atom() | If generate_type is
91 | true, this changes the type name and the function name for the conversion
92 | function. |
93 |
94 |
95 |
96 | The given examples use the following record and record defintion:
97 |
98 | ```erlang
99 | -record(person {
100 | name :: binary(),
101 | age = 0 :: pos_integer(),
102 | spouse :: #person{}
103 | }).
104 | Record = #person{ name = <<"John">>, age = 32, spouse = undefined }.
105 | ```
106 |
107 | ### to_json
108 |
109 | To convert a record to a json structure:
110 |
111 | ```erlang
112 | Json = person:to_json(Record).
113 | #{name := <<"John">>, age := 32} = Json.
114 | ```
115 |
116 | The to_json function can take a list of mutators. Mutators are applied in
117 | the order listed except {null_is_undefined}. Supported mutators are:
118 |
119 | * Turn undefined into null instead of skipping the field
120 |
121 | ```erlang
122 | person:to_json(Record, [{null_is_undefined}]).
123 | ```
124 |
125 | * Add a property
126 |
127 | ```erlang
128 | person:to_json(Record, [{single, true}]).
129 | person:to_json(Record, [#{single => true}).
130 | person:to_json(Record, [#{single => true, employed => true}).
131 | ```
132 |
133 | * Remove a property
134 |
135 | ```erlang
136 | person:to_json(Record, [age]).
137 | ```
138 |
139 | * Modify based only on the json
140 |
141 | ```erlang
142 | ModFunc = fun(Json) ->
143 | case maps:find(spouse, Json) of
144 | error ->
145 | Json#{single => true}
146 | _ ->
147 | Json#{single => false}
148 | end
149 | end.
150 | person:to_json(Record, [ModFunc]).
151 | ```
152 |
153 | * Modify based on both json and record
154 |
155 | ```erlang
156 | ModFunc = fun(Json, Record) ->
157 | case Record#person.spouse of
158 | undefined ->
159 | Json#{single => true};
160 | _ ->
161 | Json#{single => false}
162 | end
163 | end.
164 | person:to_json(Record, [ModFunc]).
165 | ```
166 |
167 | ### from_json
168 |
169 | Converting from a json structure to a record is just as simple:
170 |
171 | ```erlang
172 | {ok, Record} = person:from_json(#{
173 | <<"name">> => <<"John">>,
174 | <<"age">> => 32,
175 | <<"spouse">> => null
176 | }).
177 | ```
178 |
179 | It may be desirable to change 'null' into 'undefined' in the record:
180 |
181 | ```erlang
182 | {ok, Record} = person:from_json(Json, [null_is_undefined]).
183 | ```
184 |
185 | It may be desirable to start with an existing record instead of creating
186 | a new one:
187 |
188 | ```erlang
189 | {ok, Record2} = person:from_json(Json, Record).
190 | {ok, Record2} = person:from_json(Record, Json).
191 | {ok, Record2} = person:from_json(Record, Json, [null_is_undefined]).
192 | ```
193 |
194 | If the json structure has a type that cannot be reconciled with a type
195 | specified by the record definition, a list of fields with possible errors
196 | is returned. The record will have the data that was in the json structure.
197 | An untyped record field is the same as having the type 'any()'. There are
198 | no warnings about missing properties in the json, they simply retain the
199 | default value of the record.
200 |
201 | ```erlang
202 | {ok, Record, [age]} = person:from_json(#{<<"age">> => <<"32">>}).
203 | ```
204 |
205 | ### Including in a project
206 |
207 | If all you are using is the parse_transform, simply add rec2json as a
208 | required application.
209 |
210 | ## Type Checking and Conversion
211 |
212 | Type conversion attempts to be as transparent and intuitive as possible.
213 | There are some types that json does not represent directly, and some types
214 | that have additional checking implemented.
215 |
216 | Record fields that have atoms as types will have binary values in the json
217 | checked. If the atom converted to the binary is equal to the json value, the
218 | atom value is put into the record. When converting a record to json, atom
219 | values will be converted to binaries.
220 |
221 | Lists have their types checked. If there is an invalid type, the invalid
222 | type is placed in the list, but the warning message has the index of the
223 | invalid type placed in the warning path list. For example:
224 |
225 | ```erlang
226 | -record(list_holder, {
227 | ids :: [integer()]
228 | }).
229 |
230 | type_mismatch() ->
231 | Json = #{ids => [<<"invalid">>, 3]},
232 | {ok, Record, Warnings} = list_holder:from_json(Json),
233 | #list_holder{ids = [<<"invalid">>, 3]} = Record,
234 | [[ids, 1]] = Warnings.
235 | ```
236 |
237 | Proplists will match the first record type. A warning is emitted if that
238 | record was not compiled using rec2json (eg: RecordName:from_json/2 is not
239 | an exported function). If the compilation emits warnings, the resulting warning
240 | list has the field name prepended to each. For example:
241 |
242 | ```erlang
243 | -record(outer, {
244 | in_field :: #inner{}
245 | }).
246 | -record(inner, {
247 | count :: integer()
248 | }).
249 |
250 | type_mismatch() ->
251 | Json = #{in_field => #{count => <<"0">>}},
252 | {ok, Record, Warnings} = outer:from_json(Json),
253 | #outer{in_field = #inner{ count = <<"0">> } } = Record,
254 | [[in_filed, count]] = Warnings.
255 | ```
256 |
257 | If a record field is not typed, or has the type "any()", no warning is ever
258 | emitted for that field.
259 |
260 | Type checking comes in two flavors: built-in, and user defined.
261 |
262 | ### Built-in types
263 |
264 | Currently defined types checked:
265 |
266 | * integer()
267 | * pos_integer()
268 | * non_neg_integer()
269 | * neg_integer()
270 | * float()
271 | * number()
272 | * boolean()
273 | * binary()
274 | * [supported_type()]
275 | * #record{} when record has record:from_json/2 exported
276 | * atom (note it is not atom())*
277 | * null when converting to undefined or back
278 |
279 | The type `atom()` is not supported because a primary use case for rec2json
280 | is to convert untrusted data, such as an http post request. Converting
281 | untrusted data into atoms can exhaust the erlang vm's atom table, or worse
282 | exhaust the machine's memory. Rec2json is, by default, safe.
283 |
284 | It is still possible to apply a type to a record field so that json strings
285 | will be converted to the equivalent atom using either a user defined type,
286 | or the provided `r2j_type:unsafe_atom()` type.
287 |
288 | ### User defined types
289 |
290 | A user defined type is the same as an external type. When going to or from
291 | json, rec2json will check to see if there is a translation function
292 | matching the module and type of the type given. A translation function
293 | should have an arity 1 greater than the type has parameters. The function
294 | should either return `{ok, NewVal}` or `error`.
295 |
296 | For example, given the module:
297 |
298 | ```erlang
299 | -module(type_example).
300 | -compile([{parse_transform, rec2json}]).
301 |
302 | % These two lines exist to satisfy dialyzer.
303 | -type point() :: {number(), number()}.
304 | -export_type([point/0]).
305 |
306 | -record(type_example, {
307 | some_field :: module:function(arg1, arg2),
308 | xy = {0, 0} :: type_example:point()
309 | }).
310 |
311 | -export([point/1]).
312 |
313 | point({X,Y}) when is_number(X), is_number(Y) ->
314 | {ok, [X,Y]};
315 |
316 | point([X, Y]) when is_number(X), is_number(Y) ->
317 | {ok, {X, Y}};
318 |
319 | point(_) ->
320 | error.
321 | ```
322 |
323 | When using to_json or from_json, rec2json will check to see if `module`
324 | exports a function named `function` with arity 3. If it exists, rec2json
325 | will call the function with the args listed in the type, and the current
326 | value of the field (either from the record or from the json) prepended to
327 | the arguments.
328 |
329 | When used in `from_json`, returns `error`, and all other types have been
330 | tested, `{ok, Rec, Warnings}` is returned. When used in `to_json`, an
331 | error is thrown.
332 |
333 | ## Contributing
334 |
335 | Fork and submit a pull request with relevant tests.
336 |
--------------------------------------------------------------------------------
/ebin/rec2json.app:
--------------------------------------------------------------------------------
1 | {application, rec2json, [
2 | {description, "Compile erlang record definitions into modules to convert them to/from json easily."},
3 | {vsn, "4.0.1"},
4 | {modules, ['r2j_compile','r2j_type','rec2json']},
5 | {registered, []},
6 | {applications, [kernel,stdlib]}
7 | ]}.
8 |
--------------------------------------------------------------------------------
/rebar.config:
--------------------------------------------------------------------------------
1 | {deps, [
2 |
3 | ]}.
4 | {erl_opts, [debug_info,warn_export_vars,warn_shadow_vars,warn_obsolete_guard]}.
5 |
--------------------------------------------------------------------------------
/src/r2j_compile.erl:
--------------------------------------------------------------------------------
1 | %% Copyright 2012 Micah Warren
2 | %%
3 | %% Licensed under the Apache License, Version 2.0 (the "License");
4 | %% you may not use this file except in compliance with the License.
5 | %% You may obtain a copy of the License at
6 | %%
7 | %% http://www.apache.org/licenses/LICENSE-2.0
8 | %%
9 | %% Unless required by applicable law or agreed to in writing, software
10 | %% distributed under the License is distributed on an "AS IS" BASIS,
11 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | %% See the License for the specific language governing permissions and
13 | %% limitations under the License.
14 |
15 | -module(r2j_compile).
16 |
17 | -export([simplify_fields/1]).
18 | -export([type_declaration/2, export_type_declaration/2, export_declaration/2, export_declaration/3, additional_funcs/3]).
19 |
20 | -record(record_field, {
21 | name, name_form,
22 | default_form,
23 | typelist = [],
24 | allow_any = true
25 | }).
26 |
27 | -ifdef(TEST).
28 | -include_lib("eunit/include/eunit.hrl").
29 | -define(log(Msg, Args), ?debugFmt(Msg, Args)).
30 | -define(log(Msg), ?log(Msg, [])).
31 | -else.
32 | -define(log(Msg, Args), io:format("~s:~p " ++ Msg ++ "\n", [?MODULE, ?LINE | Args])).
33 | -define(log(Msg), ?log(Msg, [])).
34 | -endif.
35 |
36 | simplify_fields({attribute, _Line, record, {_RecName, Fields}}) ->
37 | simplify_fields(Fields, []).
38 |
39 | simplify_fields([], Acc) ->
40 | lists:reverse(Acc);
41 |
42 | simplify_fields([{record_field, Line, NameForm} | Tail], Acc) ->
43 | Name = erl_parse:normalise(NameForm),
44 | FieldRec = #record_field{name = Name, name_form = NameForm,
45 | default_form = undefined_default(Line), typelist = [undefined] },
46 | simplify_fields(Tail, [FieldRec | Acc]);
47 |
48 | simplify_fields([{record_field, _Line, NameForm, Default} | Tail], Acc) ->
49 | Name = erl_parse:normalise(NameForm),
50 | FieldRec = #record_field{name = Name, name_form = NameForm, default_form = Default},
51 | simplify_fields(Tail, [FieldRec | Acc]);
52 |
53 | simplify_fields([{typed_record_field, {record_field, Line, NameForm}, Type} | Tail], Acc) ->
54 | Name = erl_parse:normalise(NameForm),
55 | {AnyNess, Types} = extract_types(Type),
56 | AllowAny = case AnyNess of
57 | any -> true;
58 | _ -> false
59 | end,
60 | FieldRec = #record_field{name = Name, name_form = NameForm,
61 | default_form = undefined_default(Line), allow_any = AllowAny,
62 | typelist = [undefined | Types]},
63 | simplify_fields(Tail, [FieldRec | Acc]);
64 |
65 | simplify_fields([{typed_record_field, {record_field, _L1, NameForm, Default}, Type} | Tail], Acc) ->
66 | Name = erl_parse:normalise(NameForm),
67 | {AnyNess, Types} = extract_types(Type),
68 | AllowAny = case AnyNess of
69 | any ->
70 | true;
71 | _ ->
72 | false
73 | end,
74 | FieldRec = #record_field{name = Name, name_form = NameForm,
75 | default_form = Default, allow_any = AllowAny, typelist = Types},
76 | simplify_fields(Tail, [FieldRec | Acc]).
77 |
78 | undefined_default(Line) ->
79 | erl_parse:abstract(undefined, Line).
80 |
81 | extract_types({type, _L1, union, Types}) ->
82 | extract_types(Types, []);
83 | extract_types(T) when is_tuple(T) ->
84 | extract_types([T], []);
85 | extract_types(T) when is_list(T) ->
86 | extract_types(T, []).
87 |
88 | extract_types([], [undefined]) ->
89 | {any, []};
90 |
91 | extract_types([], []) ->
92 | {any, []};
93 |
94 | extract_types([], Acc) ->
95 | case lists:member(any, Acc) of
96 | true ->
97 | Acc2 = lists:delete(any, Acc),
98 | {any, Acc2};
99 | false ->
100 | {specific, Acc}
101 | end;
102 | extract_types([{type, _L1, union, Types} | Tail], Acc) ->
103 | {_Specificness, Acc2} = extract_types(Types, Acc),
104 | extract_types(Tail, Acc2);
105 | extract_types([{type, _L1, list, ListTypes} | Tail], Acc) ->
106 | ListTypes2 = extract_types(ListTypes),
107 | Acc2 = [{list, ListTypes2} | Acc],
108 | extract_types(Tail, Acc2);
109 | % when a rocord field has a type defined as list(#record{}), the resulting
110 | % type is {type, L, list, [{type, L, record, [RecordName]}]}, instead of the
111 | % usual {type, L, record, RecordName}.
112 | extract_types([{type, _L1, record, [{atom, _L2, RecordName}]} | Tail], Acc) ->
113 | % no way to know if it's a rec2json compiled record, so we'll just go with
114 | % it. If it's not (no to/from json), there's a catch for undef in the
115 | % rec2json module.
116 | extract_types(Tail, [{record, RecordName} | Acc]);
117 | extract_types([{type, _L1, Type, TypeArgs} | Tail], Acc) ->
118 | % most likely not a good idea
119 | case supported_type(Type, TypeArgs) of
120 | true ->
121 | Normalised = [erl_parse:normalise(TypeArg) || TypeArg <- TypeArgs],
122 | Acc2 = [{Type, Normalised} | Acc],
123 | extract_types(Tail, Acc2);
124 | false ->
125 | extract_types(Tail, Acc);
126 | MFA ->
127 | Acc2 = [MFA | Acc],
128 | extract_types(Tail, Acc2)
129 | end;
130 | extract_types([{remote_type, _L1, [{atom,_L2,Module},{atom,_L3,Function},Args]} | Tail], Acc) ->
131 | try [erl_parse:normalise(Abstract) || Abstract <- Args] of
132 | Normals ->
133 | extract_types(Tail, [{Module, Function, Normals} | Acc])
134 | catch
135 | _:_ ->
136 | extract_types(Tail, Acc)
137 | end;
138 | extract_types([{user_type, _, _, _} | Tail], Acc) ->
139 | extract_types(Tail, Acc);
140 | extract_types([Type | Tail], Acc) ->
141 | Acc2 = [erl_parse:normalise(Type) | Acc],
142 | extract_types(Tail, Acc2).
143 |
144 | supported_type(Type, []) ->
145 | Supported = [integer, pos_integer, non_neg_integer, neg_integer, float,
146 | number, boolean, binary],
147 | case lists:member(Type, Supported) of
148 | true ->
149 | {r2j_type, Type, []};
150 | false ->
151 | false
152 | end;
153 |
154 | supported_type(record, _) ->
155 | % no go way to know if the record is rec2json compiled or not; just have to
156 | % trust the user.
157 | true;
158 |
159 | supported_type(_,_) ->
160 | false.
161 |
162 | type_declaration(RecordName, Params) ->
163 | case proplists:get_value(generate_type, Params, true) of
164 | false ->
165 | {ok, []};
166 | true ->
167 | PropertyName = proplists:get_value(type_name, Params, RecordName),
168 | Attr = {attribute, 1, type, {PropertyName, {type, 1, record, [{atom, 1, RecordName}]},[]}},
169 | {ok, [Attr]}
170 | end.
171 |
172 | export_type_declaration(RecordName, Params) ->
173 | case proplists:get_value(generate_type, Params, true) of
174 | false ->
175 | {ok, []};
176 | true ->
177 | PropertyName = proplists:get_value(type_name, Params, RecordName),
178 | Attr = {attribute, 1, export_type, [{PropertyName, 0}]},
179 | {ok, [Attr]}
180 | end.
181 |
182 | additional_funcs(RecordName, Fields, Params) ->
183 | GenerateAccessors = proplists:get_value(generate_accessors, Params, true),
184 | AccessorFuncs = case GenerateAccessors of
185 | true -> getter_funcs(Fields);
186 | false -> []
187 | end,
188 | GenerateSetters = proplists:get_value(generate_setters, Params, true),
189 | SetterFuncs = case GenerateSetters of
190 | true -> setter_funcs(Fields);
191 | false -> []
192 | end,
193 | GenerateProperty = proplists:get_value(generate_type, Params, true),
194 | Converter = case GenerateProperty of
195 | true ->
196 | ProperyName = proplists:get_value(type_name, Params, RecordName),
197 | [converter_func(RecordName, ProperyName, length(Fields))];
198 | false -> []
199 | end,
200 | {ok, FieldListFunc} = get_field_names_func(Fields),
201 | {ok, TypeListFunc} = get_field_types_func(Fields),
202 | {ok, ToJsonA1} = to_json_arity1_func(),
203 | {ok, ToJsonA2} = to_json_arity2_func(),
204 | {ok, FromJsonA1} = from_json_arity1_func(RecordName, Fields),
205 | {ok, FromJsonA2} = from_json_arity2_func(RecordName, Fields),
206 | {ok, FromJsonA3} = from_json_arity3_func(),
207 | GrandFuncList = []
208 | ++ AccessorFuncs
209 | ++ SetterFuncs
210 | ++ [FieldListFunc]
211 | ++ [TypeListFunc]
212 | ++ Converter
213 | ++ [ToJsonA1]
214 | ++ [ToJsonA2]
215 | ++ [FromJsonA1]
216 | ++ [FromJsonA2]
217 | ++ [FromJsonA3]
218 | , {ok, GrandFuncList}.
219 |
220 | export_declaration(RecordName, Fields) ->
221 | export_declaration(RecordName, Fields, []).
222 |
223 | export_declaration(RecordName, Fields, Params) ->
224 | Line = proplists:get_value(line, Params, 1),
225 | GenerateAccessors = proplists:get_value(generate_accessors, Params, true),
226 | FieldDecs = case GenerateAccessors of
227 | true -> lists:map(fun getter_export_declaration/1, Fields);
228 | false -> []
229 | end,
230 | GenerateSetters = proplists:get_value(generate_setters, Params, true),
231 | SetFieldDecs = case GenerateSetters of
232 | true -> lists:map(fun setter_export_declaration/1, Fields);
233 | false -> []
234 | end,
235 | GenerateProperty = proplists:get_value(generate_type, Params, true),
236 | Converter = case GenerateProperty of
237 | true ->
238 | PropertyName = proplists:get_value(type_name, Params, RecordName),
239 | [{PropertyName, 1}];
240 | false -> []
241 | end,
242 | Decs = [{field_names, 0}, {field_types, 0}, {to_json, 1}, {to_json, 2},
243 | {from_json, 1}, {from_json, 2}, {from_json, 3}] ++ Converter ++ FieldDecs ++
244 | SetFieldDecs,
245 | {ok, {attribute, Line, export, Decs}}.
246 |
247 | getter_export_declaration(Rec) ->
248 | {Rec#record_field.name, 1}.
249 |
250 | setter_export_declaration(Rec) ->
251 | {Rec#record_field.name, 2}.
252 |
253 | getter_funcs(Fields) ->
254 | EndSeq = 2 + length(Fields) - 1,
255 | Ns = lists:seq(2, EndSeq),
256 | Zipped = lists:zip(Ns, Fields),
257 | lists:map(fun getter_func/1, Zipped).
258 |
259 | converter_func(RecordName, PropertyName, NumFields) ->
260 | {function,?LINE,PropertyName,1, [
261 | {clause,?LINE, [{var,?LINE,'Input'}], [], [
262 | {'case',?LINE, {call,?LINE, {remote,?LINE,{atom,?LINE,rec2json},{atom,?LINE,is_json_object}}, [{var,?LINE,'Input'}]}, [
263 | {clause,?LINE, [{atom,?LINE,true}], [], [
264 | {call,?LINE,{atom,?LINE,from_json},[{var,?LINE,'Input'}]}
265 | ]},
266 | {clause,?LINE, [{atom,?LINE,false}], [], [
267 | {'case',?LINE, {call,?LINE, {remote,?LINE,{atom,?LINE,rec2json},{atom,?LINE,is_record}}, [{var,?LINE,'Input'}, {atom,?LINE,RecordName}, {integer,?LINE,NumFields + 1}]}, [
268 | {clause,?LINE, [{atom,?LINE,true}], [], [
269 | {tuple, ?LINE, [{atom, ?LINE, ok}, {call,?LINE,{atom,?LINE,to_json},[{var,?LINE,'Input'}]}]}
270 | ]},
271 | {clause,?LINE, [{atom,?LINE,false}], [], [
272 | {atom,?LINE,error}
273 | ]}
274 | ]}
275 | ]}
276 | ]}
277 | ]}
278 | ]}.
279 |
280 | getter_func({ElementN, FieldRec}) ->
281 | {function, ?LINE, FieldRec#record_field.name, 1, [
282 | {clause, ?LINE, [{var, ?LINE, 'Record'}], [], [
283 | {call, ?LINE, {atom, ?LINE, element}, [
284 | {integer, ?LINE, ElementN},
285 | {var, ?LINE, 'Record'}
286 | ]}
287 | ]}
288 | ]}.
289 |
290 | setter_funcs(Fields) ->
291 | EndSeq = 2 + length(Fields) - 1,
292 | Ns = lists:seq(2, EndSeq),
293 | Zipped = lists:zip(Ns, Fields),
294 | lists:map(fun setter_func/1, Zipped).
295 |
296 | setter_func({ElementN, FieldRec}) ->
297 | {function, ?LINE, FieldRec#record_field.name, 2, [
298 | {clause, ?LINE, [{var, ?LINE, 'NewVal'}, {var, ?LINE, 'Record'}], [], [
299 | {call, ?LINE, {atom, ?LINE, setelement}, [{integer, ?LINE, ElementN}, {var, ?LINE, 'Record'}, {var, ?LINE, 'NewVal'}]}
300 | ]}
301 | ]}.
302 |
303 | get_field_names_func(Fields) ->
304 | NameCons = lists:foldl(fun(FieldRec, ConsAcc) ->
305 | {cons, ?LINE, FieldRec#record_field.name_form, ConsAcc}
306 | end, {nil, ?LINE}, lists:reverse(Fields)),
307 | {ok, {function, ?LINE, field_names, 0, [
308 | {clause, ?LINE, [], [], [
309 | NameCons
310 | ]}
311 | ]}}.
312 |
313 | get_field_types_func(Fields) ->
314 | TypeProps = lists:map(fun(FieldRecord) ->
315 | TypeProp = exportable_types(FieldRecord#record_field.typelist),
316 | Anyness = case FieldRecord#record_field.allow_any of
317 | true -> any;
318 | false -> specific
319 | end,
320 | {FieldRecord#record_field.name, {Anyness, TypeProp}}
321 | end, Fields),
322 | AbstractedProps = erl_parse:abstract(TypeProps),
323 | {ok, {function, ?LINE, field_types, 0, [
324 | {clause, ?LINE, [], [], [
325 | AbstractedProps
326 | ]}
327 | ]}}.
328 |
329 | exportable_types({list, ListDef}) ->
330 | Exportable = exportable_types(ListDef),
331 | {list, Exportable};
332 |
333 | exportable_types({AtomType, []}) when is_atom(AtomType) ->
334 | AtomType;
335 |
336 | exportable_types({record, [RecName]}) ->
337 | {record, RecName};
338 |
339 | exportable_types(List) when is_list(List) ->
340 | NoUndef = lists:delete(undefined, List),
341 | % the lists reverse is at the end because the earlier simplify fields
342 | % reverses the order the types were declared. By reversing it here,
343 | % the types will show up in the same ordered they ere defined for the
344 | % record.
345 | Cleansed = lists:map(fun exportable_types/1, lists:reverse(NoUndef)),
346 | case NoUndef of
347 | List ->
348 | Cleansed;
349 | _Shorter ->
350 | [undefined | Cleansed]
351 | end;
352 |
353 | exportable_types(Wut) ->
354 | Wut.
355 |
356 | to_json_arity1_func() ->
357 | {ok, {function, ?LINE, to_json, 1, [
358 | {clause, ?LINE, [{var, ?LINE, 'Struct'}], [], [
359 | {call, ?LINE, {remote, ?LINE, {atom, ?LINE, rec2json}, {atom, ?LINE, to_json}}, [{var, ?LINE, 'Struct'}, {nil, ?LINE}]}
360 | ]}
361 | ]}}.
362 |
363 | to_json_arity2_func() ->
364 | {ok, {function, ?LINE, to_json, 2, [
365 | {clause, ?LINE, [{var, ?LINE, 'Struct'}, {var, ?LINE, 'Options'}], [[{call, ?LINE, {atom, ?LINE, is_tuple}, [{var, ?LINE, 'Struct'}]}]], [
366 | {call, ?LINE, {remote, ?LINE, {atom, ?LINE, rec2json}, {atom, ?LINE, to_json}}, [{var, ?LINE, 'Struct'}, {var, ?LINE, 'Options'}]}
367 | ]},
368 | {clause, ?LINE, [{var, ?LINE, 'Options'}, {var, ?LINE, 'Struct'}], [[{call, ?LINE, {atom, ?LINE, is_tuple}, [{var, ?LINE, 'Struct'}]}]], [
369 | {call, ?LINE, {atom, ?LINE, to_json}, [{var, ?LINE, 'Struct'}, {var, ?LINE, 'Options'}]}
370 | ]}
371 | ]}}.
372 |
373 | blank_record(RecName, Fields) ->
374 | ValueListSansName = lists:map(fun(FieldRec) ->
375 | FieldRec#record_field.default_form
376 | end, Fields),
377 | ElementList = [{atom, ?LINE, RecName} | ValueListSansName],
378 | {tuple, ?LINE, ElementList}.
379 |
380 | from_json_arity1_func(RecName, Fields) ->
381 | BlankTuple = blank_record(RecName, Fields),
382 | {ok, {function, ?LINE, from_json, 1, [
383 | {clause, ?LINE, [{var, ?LINE, 'Json'}], [], [
384 | {call, ?LINE, {remote, ?LINE, {atom, ?LINE, rec2json}, {atom, ?LINE, from_json}}, [BlankTuple, {var, ?LINE, 'Json'}, {nil, ?LINE}]}
385 | ]}
386 | ]}}.
387 |
388 | from_json_arity2_func(RecName, Fields) ->
389 | BlankRec = blank_record(RecName, Fields),
390 | {ok,{function, ?LINE,from_json,2, [
391 | from_json_arity2_no_seed_json_first(BlankRec),
392 | from_json_arity2_no_seed_json_second(BlankRec),
393 | from_json_arity2_seed_first(),
394 | from_json_arity2_seed_second()
395 | ]}}.
396 |
397 | from_json_arity2_no_seed_json_first(BlankRec) ->
398 | Args = [{var, ?LINE, 'Json'}, {var, ?LINE, 'Opts'}],
399 | Guards = [[
400 | {call, ?LINE, {atom, ?LINE, is_map}, [{var, ?LINE, 'Json'}]},
401 | {call, ?LINE, {atom, ?LINE, is_list}, [{var, ?LINE, 'Opts'}]}
402 | ]],
403 | Expressions = [
404 | {call, ?LINE, {atom, ?LINE, from_json}, [BlankRec, {var, ?LINE, 'Json'}, {var, ?LINE, 'Opts'}]}
405 | ],
406 | {clause, ?LINE, Args, Guards, Expressions}.
407 |
408 | from_json_arity2_no_seed_json_second(BlankRec) ->
409 | Args = [{var, ?LINE, 'Opts'}, {var, ?LINE, 'Json'}],
410 | Guards = [[
411 | {call, ?LINE, {atom, ?LINE, is_map}, [{var, ?LINE, 'Json'}]},
412 | {call, ?LINE, {atom, ?LINE, is_list}, [{var, ?LINE, 'Opts'}]}
413 | ]],
414 | Expressions = [
415 | {call, ?LINE, {atom, ?LINE, from_json}, [BlankRec, {var, ?LINE, 'Json'}, {var, ?LINE, 'Opts'}]}
416 | ],
417 | {clause, ?LINE, Args, Guards, Expressions}.
418 |
419 | from_json_arity2_seed_first() ->
420 | Args = [{var, ?LINE, 'Struct'}, {var, ?LINE, 'Json'}],
421 | Guards = [[
422 | {call, ?LINE, {atom, ?LINE, is_tuple}, [{var, ?LINE, 'Struct'}]},
423 | {call, ?LINE, {atom, ?LINE, is_map}, [{var, ?LINE, 'Json'}]}
424 | ]],
425 | Expressions = [
426 | {call, ?LINE, {atom, ?LINE, from_json}, [{var, ?LINE, 'Struct'}, {var, ?LINE, 'Json'}, {nil, ?LINE}]}
427 | ],
428 | {clause, ?LINE, Args, Guards, Expressions}.
429 |
430 | from_json_arity2_seed_second() ->
431 | Args = [{var, ?LINE, 'Json'}, {var, ?LINE, 'Struct'}],
432 | Guards = [[
433 | {call, ?LINE, {atom, ?LINE, is_tuple}, [{var, ?LINE, 'Struct'}]},
434 | {call, ?LINE, {atom, ?LINE, is_map}, [{var, ?LINE, 'Json'}]}
435 | ]],
436 | Expressions = [
437 | {call, ?LINE, {atom, ?LINE, from_json}, [{var, ?LINE, 'Struct'}, {var, ?LINE, 'Json'}, {nil, ?LINE}]}
438 | ],
439 | {clause, ?LINE, Args, Guards, Expressions}.
440 |
441 | from_json_arity3_func() ->
442 | Gaurds = [[
443 | {call, ?LINE, {atom, ?LINE, is_tuple}, [{var, ?LINE, 'Struct'}]},
444 | {call, ?LINE, {atom, ?LINE, is_map}, [{var, ?LINE, 'Json'}]},
445 | {call, ?LINE, {atom, ?LINE, is_list}, [{var, ?LINE, 'Opts'}]}
446 | ]],
447 | RemoteCall = {call, ?LINE, {remote, ?LINE, {atom, ?LINE, rec2json},{atom,?LINE,from_json}}, [{var, ?LINE, 'Struct'}, {var, ?LINE, 'Json'}, {var, ?LINE, 'Opts'}]},
448 | ArgOrders = [
449 | ['Struct', 'Json', 'Opts'],
450 | ['Struct', 'Opts', 'Json'],
451 | ['Json', 'Struct', 'Opts'],
452 | ['Json', 'Opts', 'Struct'],
453 | ['Opts', 'Json', 'Struct'],
454 | ['Opts', 'Struct', 'Json']
455 | ],
456 | Clauses = lists:map(fun(Args) ->
457 | Vars = [{var, ?LINE, A} || A <- Args],
458 | {clause, ?LINE, Vars, Gaurds, [RemoteCall]}
459 | end, ArgOrders),
460 | {ok, {function, ?LINE, from_json, 3, Clauses}}.
461 |
--------------------------------------------------------------------------------
/src/r2j_type.erl:
--------------------------------------------------------------------------------
1 | %% @doc Module which holds and exports the custome types and validators
2 | %% which will ship with rec2json.
3 | -module(r2j_type).
4 |
5 | -export([integer/1, pos_integer/1, non_neg_integer/1, neg_integer/1, float/1,
6 | number/1, boolean/1, binary/1, unsafe_atom/1]).
7 | -export([integer/3, atom/2]).
8 | -export([string/2]).
9 |
10 | -type unsafe_atom() :: atom().
11 | -export_type([
12 | unsafe_atom/0
13 | ]).
14 |
15 |
16 | integer(N) when is_integer(N) ->
17 | {ok, N};
18 |
19 | integer(_N) ->
20 | error.
21 |
22 | pos_integer(N) when is_integer(N), 0 < N ->
23 | {ok, N};
24 | pos_integer(_N) ->
25 | error.
26 |
27 | non_neg_integer(N) when is_integer(N), 0 =< N ->
28 | {ok, N};
29 | non_neg_integer(_) ->
30 | error.
31 |
32 | neg_integer(N) when is_integer(N), N < 0 ->
33 | {ok, N};
34 | neg_integer(_) ->
35 | error.
36 |
37 | float(N) when is_float(N) ->
38 | {ok, N};
39 | float(N) when is_integer(N) ->
40 | try N * 1.0 of
41 | _ ->
42 | {ok, N}
43 | catch
44 | {error, badarith} ->
45 | error
46 | end;
47 | float(_) ->
48 | error.
49 |
50 | number(N) when is_number(N) ->
51 | {ok, N};
52 | number(_) ->
53 | error.
54 |
55 | boolean(N) when N; not N ->
56 | {ok, N};
57 | boolean(_) ->
58 | error.
59 |
60 | binary(N) when is_binary(N) ->
61 | {ok, N};
62 | binary(_) ->
63 | error.
64 |
65 | integer(N, Min, Max) when is_integer(N), Min =< N, N =< Max ->
66 | {ok, N};
67 | integer(_,_,_) ->
68 | error.
69 |
70 | atom(Bin, Atom) when is_binary(Bin) ->
71 | case list_to_binary(atom_to_list(Atom)) of
72 | Bin ->
73 | {ok, Atom};
74 | _ ->
75 | error
76 | end;
77 |
78 | atom(Atom, Atom) when is_atom(Atom) ->
79 | {ok, list_to_binary(atom_to_list(Atom))};
80 |
81 | atom(_Atom, _OtherAtom) ->
82 | error.
83 |
84 | string(Str, Len) when is_binary(Str), size(Str) =< Len ->
85 | {ok, Str};
86 | string(_Str, _Len) ->
87 | error.
88 |
89 | %% @doc Translation for any atom at all. This is marked as unsafe because if
90 | %% the json to decode is taken from an untrusted source, and you use this type
91 | %% on a field, that untrusted source could fill up your atom table. Atoms are
92 | %% not garbage collected, ever, so the untrusted source could also fill up your
93 | %% systems memory. Even a trusted source can go wonky. As such, think long and
94 | %% hard before you go ahead an use this.
95 | unsafe_atom(Atom) when is_atom(Atom) ->
96 | {ok, atom_to_binary(Atom, utf8)};
97 |
98 | unsafe_atom(Binary) when is_binary(Binary) ->
99 | {ok, binary_to_atom(Binary, utf8)};
100 |
101 | unsafe_atom(_Else) ->
102 | error.
103 |
--------------------------------------------------------------------------------
/src/rec2json.erl:
--------------------------------------------------------------------------------
1 | %% Copyright 2012 Micah Warren
2 | %%
3 | %% Licensed under the Apache License, Version 2.0 (the "License");
4 | %% you may not use this file except in compliance with the License.
5 | %% You may obtain a copy of the License at
6 | %%
7 | %% http://www.apache.org/licenses/LICENSE-2.0
8 | %%
9 | %% Unless required by applicable law or agreed to in writing, software
10 | %% distributed under the License is distributed on an "AS IS" BASIS,
11 | %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | %% See the License for the specific language governing permissions and
13 | %% limitations under the License.
14 |
15 | -module(rec2json).
16 |
17 | -ifdef(TEST).
18 | -include_lib("eunit/include/eunit.hrl").
19 | -define(log(Msg, Args), ?debugFmt(Msg, Args)).
20 | -define(log(Msg), ?log(Msg, [])).
21 | -else.
22 | -define(log(Msg, Args), io:format("~s:~p " ++ Msg ++ "\n", [?MODULE, ?LINE | Args])).
23 | -define(log(Msg), ?log(Msg, [])).
24 | -endif.
25 |
26 | -export([parse_transform/2]).
27 | -export([verify_type/5, verify_types/5]).
28 | -export([to_json/1, to_json/2]).
29 | -export([from_json/3]).
30 | -export([is_json_object/1, is_record/3]).
31 |
32 | %% ---------------------------------------------------------------------------
33 | %% parse transform
34 | %% ---------------------------------------------------------------------------
35 |
36 | parse_transform(RawForms, Options) ->
37 | PassedInParams = proplists:get_value(rec2json, Options, []),
38 | Params = lists:foldl(fun extract_param/2, PassedInParams, RawForms),
39 | %% always kinda icky to use an undocumented function.
40 | %% however, without this, the abstract record forms passed in lack the
41 | %% type information needed for user defined types to work properly.
42 | Forms = epp:restore_typed_record_fields(RawForms),
43 | ModuleName = hd([Mod || {attribute, _Line, module, Mod} <- Forms]),
44 | MaybeRecords = [R || {attribute, _Line, record, {RecordName, _Fields}} = R <- Forms, ModuleName == RecordName],
45 | case MaybeRecords of
46 | [Record] ->
47 | SimpleFields = r2j_compile:simplify_fields(Record),
48 | {ok, AdditionalExports} = r2j_compile:export_declaration(ModuleName, SimpleFields, Params),
49 | {ok, Types} = r2j_compile:type_declaration(ModuleName, Params),
50 | {ok, TypeExports} = r2j_compile:export_type_declaration(ModuleName, Params),
51 | {ok, Functions} = r2j_compile:additional_funcs(ModuleName, SimpleFields, Params),
52 | WithNewBits = insert_new_bits(Forms, AdditionalExports, Types, TypeExports, Functions, Params),
53 | lists:map(fun maybe_normalize_record_def/1, WithNewBits);
54 | _Records ->
55 | Forms
56 | end.
57 |
58 | extract_param({attribute, _Line, rec2json, Option}, Acc) when is_list(Option) ->
59 | Option ++ Acc;
60 | extract_param({attribute, _Line, rec2json, Option}, Acc) ->
61 | [Option | Acc];
62 | extract_param(_, Acc) ->
63 | Acc.
64 |
65 | maybe_normalize_record_def({attribute, Line, record, {RecordName, RecordFields}} = Form) ->
66 | case epp:normalize_typed_record_fields(RecordFields) of
67 | not_typed ->
68 | Form;
69 | {typed, NewFields} ->
70 | {attribute, Line, record, {RecordName, NewFields}}
71 | end;
72 |
73 | maybe_normalize_record_def(Form) ->
74 | Form.
75 |
76 | insert_new_bits(Forms, AllNewExports, AllNewTypes, AllNewTypeExports, AllNewFunctions, Params) ->
77 | EofSplit = fun
78 | ({eof, _}) -> false;
79 | (_) -> true
80 | end,
81 | ExportSplit = fun
82 | ({attribute, _Line, export, _Exports}) ->
83 | false;
84 | (_) ->
85 | true
86 | end,
87 | FunctionsSplit = fun
88 | ({function, _Line, _Name, _Arity, _Clauses}) ->
89 | false;
90 | (_) ->
91 | true
92 | end,
93 | {NoEof, Eof} = lists:splitwith(EofSplit, Forms),
94 | {UpToFunctions, OrigFunctions} = lists:splitwith(FunctionsSplit, NoEof),
95 | {UpToExport, ExportAndPreFunctions} = lists:splitwith(ExportSplit, UpToFunctions),
96 | {Exports, Types, ExportTypes, Functions} = case proplists:get_value(careful, Params, true) of
97 | false ->
98 | {AllNewExports, AllNewTypes, AllNewTypeExports, AllNewFunctions};
99 | true ->
100 | {careful_exports(AllNewExports, Forms), careful_type_decl(AllNewTypes, Forms), careful_type_exports(AllNewTypeExports, Forms), careful_functions(AllNewFunctions, Forms)}
101 | end,
102 | UpToExport ++ [Exports] ++ ExportAndPreFunctions ++ Types ++ ExportTypes ++ Functions ++ OrigFunctions ++ Eof.
103 |
104 | careful_exports(NewExportDecl, AllForms) ->
105 | {attribute, Line, export, NewExports} = NewExportDecl,
106 | OrigDecl = lists:foldl(fun
107 | ({attribute, _, export, Exp}, Acc) ->
108 | Exp ++ Acc;
109 | (_, Acc) ->
110 | Acc
111 | end, [], AllForms),
112 | SafeExports = NewExports -- OrigDecl,
113 | {attribute, Line, export, SafeExports}.
114 |
115 | careful_functions(NewFunctions, AllForms) ->
116 | ExistingFuncs = lists:foldl(fun
117 | ({function, _Line, Name, Arity, _Clauses}, Acc) ->
118 | [{Name, Arity} | Acc];
119 | (_, Acc) ->
120 | Acc
121 | end, [], AllForms),
122 | lists:filter(fun({function, _Line, Name, Arity, _Clauses}) ->
123 | not lists:member({Name, Arity}, ExistingFuncs)
124 | end, NewFunctions).
125 |
126 | careful_type_exports([], _) ->
127 | [];
128 |
129 | careful_type_exports(NewTypeExportDecl, AllForms) ->
130 | [{attribute, Line, export_type, NewExports}] = NewTypeExportDecl,
131 | OrigDecl = lists:foldl(fun
132 | ({attribute, _, export_type, Exp}, Acc) ->
133 | Exp ++ Acc;
134 | (_, Acc) ->
135 | Acc
136 | end, [], AllForms),
137 | SafeExports = NewExports -- OrigDecl,
138 | [{attribute, Line, export_type, SafeExports}].
139 |
140 | careful_type_decl([], _) ->
141 | [];
142 |
143 | careful_type_decl(NewTypeDecl, AllForms) ->
144 | [{attribute,_,type, {TypeName, _TypeDef, []}}] = NewTypeDecl,
145 | SameTypeCheck = fun
146 | ({attribute, _, type, {Exists, _, []}}) when TypeName =:= Exists ->
147 | true;
148 | (_) ->
149 | false
150 | end,
151 | case lists:any(SameTypeCheck, AllForms) of
152 | true ->
153 | [];
154 | false ->
155 | NewTypeDecl
156 | end.
157 |
158 | is_json_object(Term) ->
159 | is_map(Term).
160 |
161 | is_record(Input, RecordName, RecordSize) when is_tuple(Input), size(Input) == RecordSize, RecordSize >= 1, element(1, Input) =:= RecordName ->
162 | true;
163 | is_record(_, _, _) ->
164 | false.
165 |
166 | %% ---------------------------------------------------------------------------
167 | %% to json
168 | %% ---------------------------------------------------------------------------
169 |
170 | to_json(Tuple) ->
171 | to_json(Tuple, []).
172 |
173 | to_json(Tuple, Options) when is_tuple(Tuple) ->
174 | {TreatUndef, Transforms} = extract_to_json_opts(Options),
175 | [Module | Values] = tuple_to_list(Tuple),
176 | Types = Module:field_types(),
177 | ZippedFull = lists:zip(Values, Types),
178 | SkippingFields = lists:filter(fun erlang:is_atom/1, Transforms),
179 | Zipped = lists:filter(fun(Elem) ->
180 | {_Value, {Name, _FTypes}} = Elem,
181 | not lists:member(Name, SkippingFields)
182 | end, ZippedFull),
183 | {TreatUndef, ReversedJsonProps} = lists:foldl(fun
184 | ({undefined, {_Name, _FTypes}}, {skip, Acc}) ->
185 | {skip, Acc};
186 | ({undefined, {Name, _FTypes}}, {null, Acc}) ->
187 | {null, [{Name, null} | Acc]};
188 | ({Value, {Name, FTypes}}, {UndefIs, Acc}) ->
189 | case maybe_convertable(Value, FTypes, Options) of
190 | error ->
191 | erlang:error({badarg, {Name, Value, FTypes}});
192 | {ok, _NewVal, _Warns} ->
193 | erlang:error({badarg, {Name, Value, FTypes}});
194 | {ok, undefined} when UndefIs =:= skip ->
195 | {UndefIs, Acc};
196 | {ok, undefined} when UndefIs =:= null ->
197 | {UndefIs, [{Name, null} | Acc]};
198 | {ok, NewVal} when is_boolean(NewVal) ->
199 | {UndefIs, [{Name, NewVal} | Acc]};
200 | {ok, NewVal} when is_atom(NewVal) ->
201 | {UndefIs, [{Name, list_to_binary(atom_to_list(NewVal))} | Acc]};
202 | {ok, NewVal} ->
203 | {UndefIs, [{Name, NewVal} | Acc]}
204 | end
205 | end, {TreatUndef, []}, Zipped),
206 | UntransformedJson = lists:reverse(ReversedJsonProps),
207 | UntransformedMap = maps:from_list(UntransformedJson),
208 | to_json_apply_transformations(Tuple, UntransformedMap, Transforms).
209 |
210 | from_json(SeedTuple, Map, _Options) when map_size(Map) == 0 ->
211 | {ok, SeedTuple};
212 |
213 | from_json(SeedTuple, Map, Options) ->
214 | Module = element(1, SeedTuple),
215 | Names = Module:field_names(),
216 | Types = Module:field_types(),
217 | Elems = lists:seq(2, length(Names) + 1),
218 | NameBins = [atom_to_binary(N, utf8) || N <- Names],
219 | Zipper = fun(Name, TypeList, Elem) ->
220 | {Name, {Elem, TypeList}}
221 | end,
222 | Zipped = lists:zipwith3(Zipper, NameBins, Types, Elems),
223 | TreatNull = proplists:get_value(null_is_undefined, Options, false),
224 | NameMap = maps:from_list(Zipped),
225 | FoldResult = maps:fold(fun(JsonKey, JsonValue, {AccTuple, Warnings}) ->
226 | from_json_key_value(JsonKey, JsonValue, NameMap, TreatNull, AccTuple, Warnings)
227 | end, {SeedTuple, []}, Map),
228 | case FoldResult of
229 | {Record, []} ->
230 | {ok, Record};
231 | {Record, Warnings} ->
232 | {ok, Record, Warnings}
233 | end.
234 |
235 | from_json_key_value(Key, Value, TransformMap, TreatNull, AccTuple, Warnings) when is_atom(Key) ->
236 | from_json_key_value(atom_to_binary(Key, utf8), Value, TransformMap, TreatNull, AccTuple, Warnings);
237 | from_json_key_value(Key, Value, TransformMap, TreatNull, AccTuple, Warnings) ->
238 | case maps:find(Key, TransformMap) of
239 | error ->
240 | {AccTuple, Warnings};
241 | {ok, {Elem, TypeList}} ->
242 | Options = if TreatNull -> [null_is_undefined]; true -> [] end,
243 | case maybe_convertable(Value, TypeList, Options) of
244 | error ->
245 | NewAccTuple = setelement(Elem, AccTuple, Value),
246 | NewWarnings = [binary_to_atom(Key, utf8) | Warnings],
247 | {NewAccTuple, NewWarnings};
248 | {ok, Value2} ->
249 | NewAccTuple = setelement(Elem, AccTuple, Value2),
250 | {NewAccTuple, Warnings};
251 | {ok, Value2, SubWarns} ->
252 | NewAccTuple = setelement(Elem, AccTuple, Value2),
253 | NewWarnings = lists:foldr(fun(SubWarn, Warns) ->
254 | NameAtom = binary_to_atom(Key, utf8),
255 | [[NameAtom,SubWarn] | Warns]
256 | end, Warnings, SubWarns),
257 | {NewAccTuple, NewWarnings}
258 | end
259 | end.
260 |
261 | maybe_convertable(Value, any, Options) ->
262 | maybe_convertable(Value, {any, []}, Options);
263 |
264 | maybe_convertable(Value, {AnyNess, Types}, Options) ->
265 | ConvertRes = maybe_convertable(Value, Types, Options),
266 | case {ConvertRes, AnyNess} of
267 | {error, specific} ->
268 | error;
269 | {error, any} ->
270 | {ok, Value};
271 | {Else, _} ->
272 | Else
273 | end;
274 |
275 | maybe_convertable(_Value, [], _Options) ->
276 | error;
277 |
278 | maybe_convertable(Value, [{Mod, Func, Args} | Types], Options) ->
279 | Arity = length(Args) + 1,
280 | {module, _} = code:ensure_loaded(Mod),
281 | case erlang:function_exported(Mod, Func, Arity) of
282 | true ->
283 | case erlang:apply(Mod, Func, [Value | Args]) of
284 | error ->
285 | maybe_convertable(Value, Types, Options);
286 | Else ->
287 | Else
288 | end;
289 | false ->
290 | maybe_convertable(Value, Types, Options)
291 | end;
292 |
293 | maybe_convertable(null, [undefined | Types], Options) ->
294 | case proplists:get_value(null_is_undefined, Options, false) of
295 | true ->
296 | {ok, undefined};
297 | false ->
298 | maybe_convertable(null, Types, Options)
299 | end;
300 |
301 | maybe_convertable(null, [null | _Types], _Options) ->
302 | {ok, null};
303 |
304 | maybe_convertable(Value, [Atom | Types], Options) when is_atom(Atom) ->
305 | case r2j_type:atom(Value, Atom) of
306 | error ->
307 | maybe_convertable(Value, Types, Options);
308 | Else ->
309 | Else
310 | end;
311 |
312 | maybe_convertable(Tuple, [{record, RecName} | Types], Options) when is_tuple(Tuple) andalso element(1, Tuple) =:= RecName ->
313 | try RecName:to_json(Tuple, Options) of
314 | Json ->
315 | {ok, Json}
316 | catch
317 | error:undef ->
318 | maybe_convertable(Tuple, Types, Options)
319 | end;
320 |
321 | maybe_convertable(Json, [{record, RecName} | Types], Options) when is_map(Json) ->
322 | try RecName:from_json(Json, Options) of
323 | Res ->
324 | Res
325 | catch
326 | error:undef ->
327 | maybe_convertable(Json, Types, Options)
328 | end;
329 |
330 | maybe_convertable(Value, [{record, _RecName} | Types], Options) ->
331 | maybe_convertable(Value, Types, Options);
332 |
333 | maybe_convertable(Values, [{list, ListTypes} | _Types], Options) when is_list(Values) ->
334 | Indexs = lists:seq(1, length(Values)),
335 | Indexed = lists:zip(Indexs, Values),
336 | {NewValues, Warnings} = lists:foldl(fun({Index, Value}, {ValAcc, WarnAcc}) ->
337 | case maybe_convertable(Value, ListTypes, Options) of
338 | error ->
339 | {ValAcc ++ [Value], WarnAcc ++ [Index]};
340 | {ok, NewVal} ->
341 | {ValAcc ++ [NewVal], WarnAcc};
342 | {ok, NewVal, NewWarns} ->
343 | {ValAcc ++ [NewVal], WarnAcc ++ [[Index | W] || W <- NewWarns]}
344 | end
345 | end, {[], []}, Indexed),
346 | case Warnings of
347 | [] ->
348 | {ok, NewValues};
349 | _ ->
350 | {ok, NewValues, Warnings}
351 | end;
352 |
353 | maybe_convertable(Value, [{list, _ListTypes} | Types], Options) ->
354 | maybe_convertable(Value, Types, Options).
355 |
356 | to_json_apply_transformations(_Typle, Json, []) ->
357 | Json;
358 |
359 | to_json_apply_transformations(Tuple, Json, [Props | Tail]) when is_map(Props) ->
360 | Json2 = maps:merge(Json, Props),
361 | to_json_apply_transformations(Tuple, Json2, Tail);
362 |
363 | to_json_apply_transformations(Tuple, Json, [{K, V} | Tail]) ->
364 | Json2 = Json#{K => V},
365 | to_json_apply_transformations(Tuple, Json2, Tail);
366 |
367 | to_json_apply_transformations(Tuple, Json, [Atom | Tail]) when is_atom(Atom) ->
368 | Json2 = maps:remove(Atom, Json),
369 | to_json_apply_transformations(Tuple, Json2, Tail);
370 |
371 | to_json_apply_transformations(Tuple, Json, [Fun | Tail]) when is_function(Fun) ->
372 | Json2 = case erlang:fun_info(Fun, arity) of
373 | {arity, 1} ->
374 | Fun(Json);
375 | {arity, 2} ->
376 | Fun(Json, Tuple);
377 | _ ->
378 | Json
379 | end,
380 | to_json_apply_transformations(Tuple, Json2, Tail).
381 |
382 | extract_to_json_opts(Opts) ->
383 | extract_to_json_opts(Opts, skip, []).
384 |
385 | extract_to_json_opts([], TreatUndef, Acc) ->
386 | {TreatUndef, lists:reverse(Acc)};
387 |
388 | extract_to_json_opts([{null_is_undefined} | Tail], _TreatUndef, Acc) ->
389 | extract_to_json_opts(Tail, null, Acc);
390 |
391 | extract_to_json_opts([Transform | Tail], TreatUndef, Acc) ->
392 | extract_to_json_opts(Tail, TreatUndef, [Transform | Acc]).
393 |
394 | %% ---------------------------------------------------------------------------
395 | %% verify types
396 | %% ---------------------------------------------------------------------------
397 |
398 | verify_type(null, [], any, TreatNull, _RecurseOpt) ->
399 | {ok, TreatNull};
400 | verify_type(null, [], _Any, TreatNull, _RecurseOpt) ->
401 | {warn, TreatNull};
402 | verify_type(Val, [], any, _TreatNull, _RecurseOpt) ->
403 | {ok, Val};
404 | verify_type(Val, [], _Any, _TreatNull, _RecurseOpt) ->
405 | {warn, Val};
406 | verify_type(null, [NullType | _Tail], _Any, NullType, _RecurseOpt) ->
407 | {ok, NullType};
408 | %verify_type(Val, [{Type, []} | Tail], Any, Nulltype, RecurseOpt) ->
409 | % verify_type(Val, [Type | Tail], Any, Nulltype, RecurseOpt);
410 | verify_type(Val, [{integer, []} | _Tail], _Any, _TreatNull, _Opt) when is_integer(Val) ->
411 | {ok, Val};
412 | verify_type(Val, [{float, []} | _Tail], _Any, _TreatNull, _Opt) when is_float(Val) ->
413 | {ok, Val};
414 | verify_type(true, [{boolean, []} | _Tail], _Any, _TreatNull, _Opt) ->
415 | {ok, true};
416 | verify_type(false, [{boolean, []} | _Tail], _Any, _TreatNull, _Opt) ->
417 | {ok, false};
418 | verify_type(Val, [{binary, []} | _Tail], _Any, _TreatNull, _Opt) when is_binary(Val) ->
419 | {ok, Val};
420 | verify_type(Val, [{pos_integer, []} | _Tail], _Any, _TreatNull, _Opt) when is_integer(Val), Val > 0 ->
421 | {ok, Val};
422 | verify_type(Val, [{non_neg_integer, []} | _Tail], _Any, _TreatNull, _Opt) when is_integer(Val), Val > -1 ->
423 | {ok, Val};
424 | verify_type(Val, [{neg_integer, []} | _Tail], _Any, _TreatNull, _Opt) when is_integer(Val), Val < 0 ->
425 | {ok, Val};
426 | verify_type(Val, [{number, []} | _Tail], _Any, _TreatNull, _Opt) when is_number(Val) ->
427 | {ok, Val};
428 | verify_type(Val, [{float, []} | _Tail], _Any, _TreatNull, _Opt) when is_float(Val) ->
429 | {ok, Val};
430 | verify_type([{}] = Json, [{record, [RecName]} | _Tail], _Any, _TreatNull, Opt) ->
431 | verify_type_record(Json, RecName, Opt);
432 | verify_type([{_K, _V} | _OTail] = Val, [{record, [RecName]} | _Tail], _Any, _TreatNull, Opt) ->
433 | verify_type_record(Val, RecName, Opt);
434 | verify_type(Vals, [{list, {ListAny, Types}} | _Tail], _Any, TreatNull, Opt) when is_list(Vals) ->
435 | verify_types(Vals, Types, ListAny, TreatNull, Opt);
436 | verify_type(Val, [Atom | Tail], Any, TreatNull, Opt) when is_binary(Val), is_atom(Atom) ->
437 | case list_to_binary(atom_to_list(Atom)) of
438 | Val ->
439 | {ok, Atom};
440 | _ ->
441 | verify_type(Val, Tail, Any, TreatNull, Opt)
442 | end;
443 | verify_type(Val, [{Module, Function, Args} | Tail], Any, TreatNull, Opt) ->
444 | case erlang:function_exported(Module, Function, length(Args) + 1) of
445 | true ->
446 | case erlang:apply(Module, Function, [Val | Args]) of
447 | true ->
448 | {ok, Val};
449 | {ok, NewVal} ->
450 | {ok, NewVal};
451 | false ->
452 | {warn, Val}
453 | end;
454 | false ->
455 | verify_type(Val, Tail, Any, TreatNull, Opt)
456 | end;
457 | verify_type(Val, [_Type | Tail], Any, TreatNull, Opt) ->
458 | verify_type(Val, Tail, Any, TreatNull, Opt).
459 |
460 | verify_type_record(Json, RecName, Opt) ->
461 | case erlang:function_exported(RecName, from_json, 2) of
462 | true ->
463 | case RecName:from_json(Json, Opt) of
464 | {ok, Rec} ->
465 | {ok, Rec};
466 | {ok, Rec, Warns} ->
467 | {warn, Rec, Warns}
468 | end;
469 | false ->
470 | case code:ensure_loaded(RecName) of
471 | {error, _} ->
472 | {warn, Json};
473 | {module, RecName} ->
474 | verify_type_record(Json, RecName, Opt)
475 | end
476 | end.
477 |
478 | verify_types(Vals, Types, Any, TreatNull, Opt) ->
479 | verify_types(Vals, Types, Any, TreatNull, Opt, 1, [], []).
480 |
481 | verify_types([], _Types, _Any, _TreatNull, _Opt, _Index, WarnIndexes, Acc) ->
482 | Acc1 = lists:reverse(Acc),
483 | case WarnIndexes of
484 | [] ->
485 | {ok, Acc1};
486 | _ ->
487 | Indexes = lists:reverse(WarnIndexes),
488 | {warn, Acc1, Indexes}
489 | end;
490 | verify_types([Val | Tail], Types, Any, TreatNull, Opt, Index, WarnInd, Acc) ->
491 | case verify_type(Val, Types, Any, TreatNull, Opt) of
492 | {ok, Val1} ->
493 | verify_types(Tail, Types, Any, TreatNull, Opt, Index + 1, WarnInd, [Val1 | Acc]);
494 | {warn, Val1} ->
495 | verify_types(Tail, Types, Any, TreatNull, Opt, Index + 1, [Index | WarnInd], [Val1 | Acc]);
496 | {warn, Val1, Paths} when is_list(Paths) ->
497 | Paths1 = [[Index | Path] || Path <- Paths],
498 | verify_types(Tail, Types, Any, TreatNull, Opt, Index + 1, [Paths1 | WarnInd], [Val1 | Acc]);
499 | {warn, Val1, Path} ->
500 | Path1 = [Index, Path],
501 | verify_types(Tail, Types, Any, TreatNull, Opt, Index + 1, [Path1 | WarnInd], [Val1 | Acc])
502 | end.
503 |
--------------------------------------------------------------------------------
/test/careful_tests.erl:
--------------------------------------------------------------------------------
1 | -module(careful_tests).
2 | -compile([{parse_transform, rec2json}]).
3 |
4 | -ifdef(TEST).
5 | -include_lib("eunit/include/eunit.hrl").
6 |
7 | -export([to_json/1, careful_tests/1]).
8 |
9 | -record(careful_tests, {
10 | one_field
11 | }).
12 | -type careful_tests() :: #careful_tests{}.
13 | -export_type([careful_tests/0]).
14 |
15 | % the real test is if this compiles or not. By deafult, rec2json should
16 | % not stomp on existing functions, even if this would prevent the module
17 | % from working properly.
18 |
19 | to_json(Rec) ->
20 | to_json([one_field], Rec).
21 |
22 | is_careful_test() -> ?assert(true).
23 |
24 | to_json_test() ->
25 | Rec = #careful_tests{one_field = <<"yo">>},
26 | ?assertEqual(#{}, to_json(Rec)).
27 |
28 | careful_tests(Value) ->
29 | {ok, ok, Value}.
30 |
31 | use_careful_tests_function_test() ->
32 | ?assertEqual({ok, ok, <<"data">>}, careful_tests(<<"data">>)).
33 |
34 | -endif.
35 |
--------------------------------------------------------------------------------
/test/default_property.erl:
--------------------------------------------------------------------------------
1 | -module(default_property).
2 | -compile([{parse_transform, rec2json}]).
3 |
4 | -record(default_property, {
5 | f1 = 1 :: integer(),
6 | f2 = <<"hi">> :: binary()
7 | }).
8 |
--------------------------------------------------------------------------------
/test/default_value_tests.erl:
--------------------------------------------------------------------------------
1 | -module(default_value_tests).
2 | -compile([{parse_transform, rec2json}]).
3 |
4 | -ifdef(TEST).
5 | -include_lib("eunit/include/eunit.hrl").
6 |
7 | -record(sub_rec, {}).
8 | -record(record_name, {field_name = <<"record_name_field">>}).
9 |
10 | -record(default_value_tests, {
11 | integer_no_type = 3,
12 | integer_with_type = 7 :: integer(),
13 | binary_no_type = <<"yo">>,
14 | binary_with_type = <<"heya">> :: binary(),
15 | integer_list_no_type = [8,3],
16 | integer_list_with_type = [27, 89, 32] :: [integer()],
17 | tuple = {undefined, 3},
18 | list_of_tuples = [{1,2,3}, {4,5,6}, {7,8,0}],
19 | list_of_list_of_integers = [[1,2,3], [4,5,6], [7,8,9]],
20 | record_name = #record_name{},
21 | record_name_field_is_1 = #record_name{field_name = 1},
22 | record_with_sub_rec = #record_name{field_name = #sub_rec{}},
23 | record_part_of_tuple = {1, #record_name{}},
24 | record_part_of_list = [#record_name{}, 1, "Der string"],
25 | local_func_call = make_default(),
26 | local_func_call_with_arg = make_default(27),
27 | remote_func_call = ?MODULE:make_default(),
28 | remote_func_call_with_arg = ?MODULE:make_default(87),
29 | cons = [a|b]
30 | }).
31 |
32 | -export([make_default/0, make_default/1]).
33 |
34 | make_default() ->
35 | make_default(ok).
36 |
37 | make_default(Val) ->
38 | {default, Val}.
39 |
40 | defaults_test_() ->
41 | {ok, Rec} = default_value_tests:from_json(#{}),
42 |
43 | Expectations = [
44 | {integer_no_type, 3},
45 | {integer_with_type, 7},
46 | {binary_no_type, <<"yo">>},
47 | {binary_with_type, <<"heya">>},
48 | {integer_list_no_type, [8,3]},
49 | {integer_list_with_type, [27, 89, 32]},
50 | {tuple, {undefined, 3}},
51 | {list_of_tuples, [{1,2,3}, {4,5,6}, {7,8,0}]},
52 | {list_of_list_of_integers, [[1,2,3], [4,5,6], [7,8,9]]},
53 | {record_name, #record_name{}},
54 | {record_name_field_is_1, #record_name{field_name = 1}},
55 | {record_with_sub_rec, #record_name{field_name = #sub_rec{}}},
56 | {record_part_of_tuple, {1, #record_name{}}},
57 | {record_part_of_list, [#record_name{}, 1, "Der string"]},
58 | {local_func_call, make_default()},
59 | {local_func_call_with_arg, make_default(27)},
60 | {remote_func_call, ?MODULE:make_default()},
61 | {remote_func_call_with_arg, ?MODULE:make_default(87)},
62 | {cons, [a|b]}
63 | ],
64 |
65 | lists:map(fun({Field, Value}) ->
66 | create_default_test(Field, Value, Rec)
67 | end, Expectations).
68 |
69 | -ifdef(OTP_RELEASE).
70 |
71 | -if(?OTP_RELEASE >= 21).
72 |
73 | create_default_test(Field, Value, Rec) ->
74 | Name = iolist_to_binary(io_lib:format("ensure ~p is ~p", [Field, Value])),
75 | {Name, fun() ->
76 | ?assertEqual(Value, erlang:apply(?MODULE, Field, [Rec]))
77 | end}.
78 |
79 | -else.
80 |
81 | create_default_test(Field, Value, Rec) ->
82 | Name = iolist_to_binary(io_lib:format("ensure ~p is ~p", [Field, Value])),
83 | {Name, fun() ->
84 | ?assertEqual(Value, erlang:apply(?MODULE, Field, [Rec])),
85 | ?assertEqual(Value, erlang:apply(Rec, Field, []))
86 | end}.
87 |
88 | -endif.
89 |
90 | -else.
91 |
92 | create_default_test(Field, Value, Rec) ->
93 | Name = iolist_to_binary(io_lib:format("ensure ~p is ~p", [Field, Value])),
94 | {Name, fun() ->
95 | ?assertEqual(Value, erlang:apply(?MODULE, Field, [Rec])),
96 | ?assertEqual(Value, erlang:apply(Rec, Field, []))
97 | end}.
98 |
99 | -endif.
100 |
101 | -endif.
102 |
--------------------------------------------------------------------------------
/test/prop_test_rec.erl:
--------------------------------------------------------------------------------
1 | -module(prop_test_rec).
2 | -compile([{parse_transform, rec2json}]).
3 |
4 | -include("prop_test_rec.hrl").
5 |
--------------------------------------------------------------------------------
/test/prop_test_rec.hrl:
--------------------------------------------------------------------------------
1 |
2 | -include("prop_test_rec_inner.hrl").
3 |
4 | -type user_type() :: user_type.
5 |
6 | -record(prop_test_rec, {
7 | prop_integer :: integer(),
8 | prop_pos_integer :: pos_integer(),
9 | prop_int_or_bool :: integer() | boolean(),
10 | prop_atoms :: init | ready | steady,
11 | prop_non_neg_integer :: non_neg_integer(),
12 | prop_boolean :: boolean(),
13 | prop_neg_integer :: neg_integer(),
14 | prop_number :: number(),
15 | prop_binary :: binary(),
16 | prop_float :: float(),
17 | prop_list_one :: [integer()],
18 | prop_record_one_inner :: #prop_test_rec_inner{},
19 | prop_record_list :: [#prop_test_rec_inner{}],
20 | prop_user_type :: user_type(),
21 | prop_user_type_default = 3 :: user_type(),
22 | prop_user_type_list :: [user_type()],
23 | prop_r2j_integer_type :: r2j_type:integer(),
24 | prop_r2j_integer_min_max_type :: r2j_type:integer(-100, 100),
25 | prop_r2j_integer_min_max_listed :: [r2j_type:integer(-100, 100)],
26 | type_translation :: r2j_compile_tests:point(),
27 | prop_null :: null,
28 | prop_any,
29 | prop_int_with_default = 1 :: integer()
30 | }).
31 |
--------------------------------------------------------------------------------
/test/prop_test_rec_inner.erl:
--------------------------------------------------------------------------------
1 | -module(prop_test_rec_inner).
2 | -compile([{parse_transform, rec2json}]).
3 |
4 | -include("prop_test_rec_inner.hrl").
5 |
--------------------------------------------------------------------------------
/test/prop_test_rec_inner.hrl:
--------------------------------------------------------------------------------
1 | -record(prop_test_rec_inner, {f :: integer()}).
2 |
--------------------------------------------------------------------------------
/test/r2j_compile_tests.erl:
--------------------------------------------------------------------------------
1 | -module(r2j_compile_tests).
2 |
3 | -include_lib("proper/include/proper.hrl").
4 | -include_lib("eunit/include/eunit.hrl").
5 | -include("test/r2j_compile_tests.hrl").
6 | -include("test/test_rec.hrl").
7 | -include("prop_test_rec.hrl").
8 |
9 | -type point() :: {float(), float()}.
10 | -export_type([point/0]).
11 | -export([point/1]).
12 |
13 | -define(TEST_DIRECTORY, "test/").
14 |
15 | types_gen([]) ->
16 | [];
17 | types_gen([{Nth, Type} | Tail]) ->
18 | Generator = fun() ->
19 | types_gen(Tail)
20 | end,
21 | RecordStr = "-record(cst5_" ++ Nth ++ ", {f " ++ Type ++ "}).",
22 | Test = fun() ->
23 | r2j_compile:scan_string(RecordStr, [{output_dir, ?TEST_DIRECTORY}]),
24 | Module = list_to_atom("cst5_" ++ Nth),
25 | code:load_file(Module),
26 | ?assert(erlang:function_exported(Module, to_json, 1))
27 | end,
28 | {generator, fun() -> [{Type, Test} | {generator, Generator}] end}.
29 |
30 | parse_transform_test_() ->
31 | [
32 |
33 | % while the module is likely already compiled once, we don't want to
34 | % have to potentially keep doing a clean just to ensure changes to the
35 | % parse transform don't break stuff, thus the recompiles here.
36 | {"compile", fun() ->
37 | Got = compile:file(?TEST_DIRECTORY ++ "test_rec", [{outdir, ?TEST_DIRECTORY}]),
38 | ?assertEqual({ok, test_rec}, Got)
39 | end},
40 |
41 | {"The new module can be loaded", fun() ->
42 | {ok, _Module, Binary} = compile:file(?TEST_DIRECTORY ++ "test_rec", [binary]),
43 | ?assertEqual({module, test_rec}, code:load_binary(test_rec, ?TEST_DIRECTORY ++ "test_rec", Binary))
44 | end},
45 |
46 | {"has to_json/1", fun() ->
47 | ?assert(erlang:function_exported(test_rec, to_json, 1))
48 | end},
49 |
50 | {"compile a second with functions", fun() ->
51 | Got = compile:file(?TEST_DIRECTORY ++ "test_person", [{outdir, ?TEST_DIRECTORY}]),
52 | ?assertEqual({ok, test_person}, Got)
53 | end},
54 |
55 | {"Can load test_person", fun() ->
56 | {ok, _Module, Binary} = compile:file(?TEST_DIRECTORY ++ "test_person", [binary]),
57 | ?assertEqual({module, test_person}, code:load_binary(test_person, ?TEST_DIRECTORY ++ "test_person", Binary))
58 | end},
59 |
60 | {"has originally defined function", fun() ->
61 | ?assertNot(test_person:is_married(#test_person{}))
62 | end},
63 |
64 | {"has to_json/1", fun() ->
65 | ?assert(erlang:function_exported(test_person, to_json, 1))
66 | end},
67 |
68 | {"has accessor", fun() ->
69 | ?assert(erlang:function_exported(test_person, name, 1))
70 | end},
71 |
72 | {"has getters", fun() ->
73 | ?assert(erlang:function_exported(test_person, name, 2))
74 | end},
75 |
76 | {"compile and load with no accessors", fun() ->
77 | {ok, _Module, Binary} = compile:file(?TEST_DIRECTORY ++ "test_person", [binary, {rec2json, [{generate_accessors, false}]}]),
78 | Got = code:load_binary(test_person, ?TEST_DIRECTORY ++ "test_no_accessor", Binary),
79 | ?assertEqual({module, test_person}, Got)
80 | end},
81 |
82 | {"no accessor compile doesn't have accessor", fun() ->
83 | ?assertNot(erlang:function_exported(test_person, name, 1))
84 | end},
85 |
86 | {"no accessor still has to and from json", fun() ->
87 | ?assert(erlang:function_exported(test_person, to_json, 1)),
88 | ?assert(erlang:function_exported(test_person, from_json, 1))
89 | end},
90 |
91 | {"has getters", fun() ->
92 | ?assert(erlang:function_exported(test_person, name, 2))
93 | end},
94 |
95 | {"compile and load with no settors", fun() ->
96 | {ok, _Module, Binary} = compile:file(?TEST_DIRECTORY ++ "test_person", [binary, {rec2json, [{generate_setters, false}]}]),
97 | Got = code:load_binary(test_person, ?TEST_DIRECTORY ++ "test_no_setters", Binary),
98 | ?assertEqual({module, test_person}, Got)
99 | end},
100 |
101 | {"has no setters", fun() ->
102 | ?assertNot(erlang:function_exported(test_person, name, 2))
103 | end},
104 |
105 | {"no setters has accessor", fun() ->
106 | ?assert(erlang:function_exported(test_person, name, 1))
107 | end},
108 |
109 | {"no setters has to/from json", fun() ->
110 | ?assert(erlang:function_exported(test_person, to_json, 1)),
111 | ?assert(erlang:function_exported(test_person, from_json, 1))
112 | end},
113 |
114 | {"compile with no accessors or setters", fun() ->
115 | {ok, _Module, Binary} = compile:file(?TEST_DIRECTORY ++ "test_person", [
116 | binary,
117 | {rec2json, [
118 | {generate_setters, false},
119 | {generate_accessors, false}
120 | ]}
121 | ]),
122 | Got = code:load_binary(test_person, ?TEST_DIRECTORY ++ "test_no_getset", Binary),
123 | ?assertEqual({module, test_person}, Got)
124 | end},
125 |
126 | {"has no setters", fun() ->
127 | ?assertNot(erlang:function_exported(test_person, name, 1))
128 | end},
129 |
130 | {"has no getter", fun() ->
131 | ?assertNot(erlang:function_exported(test_person, name, 2))
132 | end},
133 |
134 | {"has to/from json", fun() ->
135 | ?assert(erlang:function_exported(test_person, to_json, 1)),
136 | ?assert(erlang:function_exported(test_person, from_json, 1))
137 | end},
138 |
139 | {"has default conversion function", fun() ->
140 | Exported = default_property:module_info(exports),
141 | ?assert(lists:member({default_property, 1}, Exported))
142 | end},
143 |
144 | {"default property conversion works as expected", fun() ->
145 | InitialJson = #{},
146 | {ok, Record} = default_property:default_property(InitialJson),
147 | 1 = default_property:f1(Record),
148 | <<"hi">> = default_property:f2(Record),
149 | EmptyRec = default_property:f1(undefined, default_property:f2(undefined, Record)),
150 | {ok, #{}} = default_property:default_property(EmptyRec)
151 | end},
152 |
153 | {"property name can be altered", fun() ->
154 | Exported = renamed_property:module_info(exports),
155 | ?assert(lists:member({goober, 1}, Exported))
156 | end},
157 |
158 | {"renamed property works like default", fun() ->
159 | InitialJson = #{},
160 | {ok, Record} = renamed_property:goober(InitialJson),
161 | 42 = renamed_property:f1(Record),
162 | hello = renamed_property:f2(Record),
163 | EmptyRec = renamed_property:f1(undefined, renamed_property:f2(undefined, Record)),
164 | {ok, #{}} = renamed_property:goober(EmptyRec)
165 |
166 | end},
167 |
168 | {"property creation suppressed", fun() ->
169 | Exported = suppress_property:module_info(exports),
170 | ?assertNot(lists:member({suppress_property, 1}, Exported))
171 | end}
172 |
173 | ].
174 |
175 | feature_test_() -> [
176 | {"to json", fun() ->
177 | Record = #prop_test_rec{},
178 | ?assertEqual(#{prop_int_with_default => 1, prop_user_type_default => 3}, prop_test_rec:to_json(Record))
179 | end},
180 |
181 | {"to json, undefined is null", fun() ->
182 | Record = #prop_test_rec{},
183 | [prop_test_rec | OtherValues] = tuple_to_list(Record),
184 | NulledValues = lists:map(fun
185 | (undefined) -> null;
186 | (V) -> V
187 | end, OtherValues),
188 | Json = prop_test_rec:to_json([{null_is_undefined}], Record),
189 | JsonAsList = maps:to_list(Json),
190 | Winnowed = lists:foldl(fun({_, V}, Acc) ->
191 | Acc -- [V]
192 | end, NulledValues, JsonAsList),
193 | ?assertEqual([], Winnowed)
194 | end},
195 |
196 | {"To json with adding prop mutator", fun() ->
197 | Record = #prop_test_rec{},
198 | ?assertMatch(#{newage := <<"hi">>}, prop_test_rec:to_json(Record, [{newage, <<"hi">>}]))
199 | end},
200 |
201 | {"To json with adding prop mutator as map", fun() ->
202 | Record = #prop_test_rec{},
203 | ?assertMatch(#{foo := <<"bar">>, baz := 3}, prop_test_rec:to_json(Record, [#{foo => <<"bar">>, baz => 3}]))
204 | end},
205 |
206 | {"To json with removing prop mutator", fun() ->
207 | Record = #prop_test_rec{prop_integer = 75},
208 | Json = prop_test_rec:to_json(Record, [prop_integer]),
209 | ?assertEqual(error, maps:find(prop_integer, Json))
210 | end},
211 |
212 | {"To json with arity 1 fun mutator", fun() ->
213 | Mutator1 = fun(_) ->
214 | #{}
215 | end,
216 | Mutator2 = fun(J) ->
217 | J#{fart_jokes => true}
218 | end,
219 | Expected = #{fart_jokes => true},
220 | Record = #prop_test_rec{},
221 | ?assertEqual(Expected, prop_test_rec:to_json(Record, [Mutator1, Mutator2]))
222 | end},
223 |
224 | {"To json with arity 2 fun mutator", fun() ->
225 | Record = #prop_test_rec{},
226 | Mutator = fun(_, R) ->
227 | ?assertEqual(Record, R),
228 | #{flerb => 5}
229 | end,
230 | ?assertEqual(#{flerb => 5}, prop_test_rec:to_json(Record, [Mutator]))
231 | end},
232 |
233 | {"To json with all mutators", fun() ->
234 | Record = #prop_test_rec{prop_integer = 3},
235 | A1 = fun(J) ->
236 | ?assertMatch(#{new1 := <<"hi">>}, J),
237 | J#{mut1 => 1}
238 | end,
239 | A2 = fun(J, R) ->
240 | ?assertEqual(Record, R),
241 | J#{mut2 => 2}
242 | end,
243 | Mutators = [field, prop_int_with_default, prop_user_type_default, prop_integer, {new1, <<"hi">>}, A1, A2, #{new2 => 94, new3 => <<"yo">>}],
244 | Expected = #{mut2 => 2, mut1 => 1, new1 => <<"hi">>, new2 => 94, new3 => <<"yo">>},
245 | ?assertEqual(Expected, prop_test_rec:to_json(Record, Mutators))
246 | end},
247 |
248 | {"To json, sub record encoded as empty obj", fun() ->
249 | IncRec = #prop_test_rec_inner{},
250 | Record = #prop_test_rec{prop_record_one_inner = IncRec},
251 | ?assertMatch(#{prop_record_one_inner := #{}}, prop_test_rec:to_json(Record, []))
252 | end},
253 |
254 | {"To json, sub record fully encoded", fun() ->
255 | IncRec = #prop_test_rec_inner{f = 7},
256 | Record = #prop_test_rec{prop_record_one_inner = IncRec},
257 | ?assertMatch(#{prop_record_one_inner := #{f := 7}}, prop_test_rec:to_json(Record))
258 | end},
259 |
260 | {"To json, atom becomes binary", fun() ->
261 | ?debugFmt("~p", [proplists:get_value(r2j_compile, code:all_loaded())]),
262 | Record = #prop_test_rec{prop_atoms = init},
263 | ?assertMatch(#{prop_atoms := <<"init">>}, prop_test_rec:to_json(Record))
264 | end},
265 |
266 | {"To json, true does not become binary", fun() ->
267 | ?debugFmt("~p", [proplists:get_value(r2j_compile, code:all_loaded())]),
268 | Record = #prop_test_rec{prop_boolean = true},
269 | ?assertMatch(#{prop_boolean := true}, prop_test_rec:to_json(Record))
270 | end},
271 |
272 | {"To json, false does not become binary", fun() ->
273 | ?debugFmt("~p", [proplists:get_value(r2j_compile, code:all_loaded())]),
274 | Record = #prop_test_rec{prop_boolean = false},
275 | ?assertMatch(#{prop_boolean := false}, prop_test_rec:to_json(Record))
276 | end},
277 |
278 | {"To json, empty lists stay lists", fun() ->
279 | Record = #prop_test_rec{prop_list_one = []},
280 | ?assertMatch(#{prop_list_one := []}, prop_test_rec:to_json(Record))
281 | end},
282 |
283 | {"from json with binary fields", fun() ->
284 | Expected = #prop_test_rec{prop_binary = <<"field">>},
285 | {ok, Got} = prop_test_rec:from_json(#{<<"prop_binary">> => <<"field">>}),
286 | ?assertEqual(<<"field">>, Got#prop_test_rec.prop_binary),
287 | ?assertEqual({ok, Expected}, prop_test_rec:from_json(#{<<"prop_binary">> => <<"field">>}))
288 | end},
289 |
290 | {"from json with atom field", fun() ->
291 | Expected = #prop_test_rec{prop_binary = <<"field">>},
292 | ?assertEqual({ok, Expected}, prop_test_rec:from_json(#{prop_binary => <<"field">>}))
293 | end},
294 |
295 | {"from empty json object", fun() ->
296 | Expected = #prop_test_rec{},
297 | ?assertEqual({ok, Expected}, prop_test_rec:from_json(#{}))
298 | end},
299 |
300 | {"from json object with unspecified field", fun() ->
301 | Expected = #prop_test_rec{},
302 | Json = #{thang => 71},
303 | ?assertEqual({ok, Expected}, prop_test_rec:from_json(Json))
304 | end},
305 |
306 | {"from json with seed record", fun() ->
307 | Seed = #prop_test_rec{prop_integer = 32},
308 | ?assertEqual({ok, Seed}, prop_test_rec:from_json(Seed, #{}))
309 | end},
310 |
311 | {"from json with null as null", fun() ->
312 | Expected = #prop_test_rec{prop_integer = null},
313 | Json = #{prop_integer => null},
314 | ?assertEqual({ok, Expected, [prop_integer]}, prop_test_rec:from_json(Json))
315 | end},
316 |
317 | {"from json with null as undefined", fun() ->
318 | Expected = #prop_test_rec{prop_integer = undefined},
319 | Json = #{prop_integer => null},
320 | ?assertEqual({ok, Expected}, prop_test_rec:from_json(Json, [null_is_undefined]))
321 | end},
322 |
323 | {"from json with options and seed record", [
324 | {"pure module null is null", fun() ->
325 | Expected = #prop_test_rec{prop_null = null},
326 | Json = #{prop_null => null},
327 | Seed = #prop_test_rec{prop_null = 32},
328 | ?assertEqual({ok, Expected}, prop_test_rec:from_json(Json, [], Seed))
329 | end},
330 |
331 | {"pure module null is undefined", fun() ->
332 | Expected = #prop_test_rec{prop_integer = undefined},
333 | Json = #{prop_integer => null},
334 | Seed = #prop_test_rec{prop_integer = 32},
335 | ?assertEqual({ok, Expected}, prop_test_rec:from_json(Json, [null_is_undefined], Seed))
336 | end}
337 | ]},
338 |
339 | {"from json with included record", fun() ->
340 | Expected = #prop_test_rec{prop_record_one_inner = #prop_test_rec_inner{}},
341 | Json = #{prop_record_one_inner => #{}},
342 | ?assertEqual({ok, Expected}, prop_test_rec:from_json(Json))
343 | end},
344 |
345 | {"from json with a list of included records", fun() ->
346 | Expected = #prop_test_rec{prop_record_list = [
347 | #prop_test_rec_inner{f = 1},
348 | #prop_test_rec_inner{f = 2}
349 | ]},
350 | Json = #{prop_record_list => [
351 | #{f => 1},
352 | #{f => 2}
353 | ]},
354 | ?assertEqual({ok, Expected}, prop_test_rec:from_json(Json))
355 | end},
356 |
357 | {"from json with type mismatch: integer", fun() ->
358 | Expected = #prop_test_rec{prop_integer = <<"hi">>},
359 | Json = #{prop_integer => <<"hi">>},
360 | ?assertEqual({ok, Expected, [prop_integer]}, prop_test_rec:from_json(Json))
361 | end},
362 |
363 | {"from json with type mismatch: boolean", fun() ->
364 | Expected = #prop_test_rec{prop_boolean = 42},
365 | Json = #{prop_boolean => 42},
366 | ?assertEqual({ok, Expected, [prop_boolean]}, prop_test_rec:from_json(Json))
367 | end},
368 |
369 | {"from json with type mismatch: binary", fun() ->
370 | Expected = #prop_test_rec{prop_binary = false},
371 | Json = #{prop_binary => false},
372 | ?assertEqual({ok, Expected, [prop_binary]}, prop_test_rec:from_json(Json))
373 | end},
374 |
375 | {"from json with type mismatch: list", fun() ->
376 | Expected = #prop_test_rec{prop_list_one = <<"vida loca">>},
377 | Json = #{prop_list_one => <<"vida loca">>},
378 | Got = prop_test_rec:from_json(Json),
379 | ?assertEqual({ok, Expected, [prop_list_one]}, Got)
380 | end},
381 |
382 | {"from json with type mismatch: list 2", fun() ->
383 | Expected = #prop_test_rec{prop_list_one= [<<"hi">>]},
384 | Json = #{prop_list_one => [<<"hi">>]},
385 | ?assertEqual({ok, Expected, [[prop_list_one, 1]]}, prop_test_rec:from_json(Json))
386 | end},
387 |
388 | {"from json with type mismatch: null", fun() ->
389 | Expected = #prop_test_rec{prop_null = <<"hi">>},
390 | Json = #{prop_null => <<"hi">>},
391 | ?assertEqual({ok, Expected, [prop_null]}, prop_test_rec:from_json(Json))
392 | end},
393 |
394 | {"from json with type mismatch: record_type", fun() ->
395 | Expected = #prop_test_rec{prop_record_one_inner = 33},
396 | Json = #{prop_record_one_inner => 33},
397 | ?assertEqual({ok, Expected, [prop_record_one_inner]}, prop_test_rec:from_json(Json))
398 | end},
399 |
400 | {"from json any field causes no warnings", fun() ->
401 | Expected = #prop_test_rec{prop_any = #{f => 4}},
402 | Json = #{prop_any => #{ f => 4}},
403 | ?assertEqual({ok, Expected}, prop_test_rec:from_json(Json))
404 | end},
405 |
406 | {"Accessor functions", fun() ->
407 | UnsetRecord = #prop_test_rec_inner{},
408 | Fields = record_info(fields, prop_test_rec_inner),
409 | NameAndN = lists:zip(Fields, lists:seq(2, length(Fields) + 1)),
410 | Record = lists:foldl(fun({_, N}, Acc) ->
411 | Rando = rand:uniform(),
412 | setelement(N, Acc, Rando)
413 | end, UnsetRecord, NameAndN),
414 | Test = fun({Accessor, Nth}) ->
415 | Expected = element(Nth, Record),
416 | ?assertEqual(Expected, prop_test_rec_inner:Accessor(Record))
417 | end,
418 | lists:map(Test, NameAndN)
419 | end},
420 |
421 | {"setter functions", fun() ->
422 | Record = #prop_test_rec{},
423 | Fields = record_info(fields, prop_test_rec),
424 | NameAndN = lists:zip(Fields, lists:seq(2, length(Fields) + 1)),
425 | Test = fun({Setter, Nth}) ->
426 | R1 = prop_test_rec:Setter(Nth, Record),
427 | ?assertEqual(Nth, prop_test_rec:Setter(R1)),
428 | R2 = prop_test_rec:Setter(goober, R1),
429 | ?assertEqual(goober, prop_test_rec:Setter(R2))
430 | end,
431 | lists:map(Test, NameAndN)
432 | end},
433 |
434 | {"Field list function", fun() ->
435 | Fields = record_info(fields, prop_test_rec),
436 | Got = prop_test_rec:field_names(),
437 | ?assertEqual(Fields, Got)
438 | end},
439 |
440 | {"Types list", fun() ->
441 | Fields = record_info(fields, prop_test_rec),
442 | Got = prop_test_rec:field_types(),
443 | Types = [
444 | {specific, [undefined, {r2j_type, integer, []}]},
445 | {specific, [undefined, {r2j_type, pos_integer, []}]},
446 | {specific, [undefined, {r2j_type, integer, []}, {r2j_type, boolean, []}]},
447 | {specific, [undefined, init, ready, steady]},
448 | {specific, [undefined, {r2j_type, non_neg_integer, []}]},
449 | {specific, [undefined, {r2j_type, boolean, []}]},
450 | {specific, [undefined, {r2j_type, neg_integer, []}]},
451 | {specific, [undefined, {r2j_type, number, []}]},
452 | {specific, [undefined, {r2j_type, binary, []}]},
453 | {specific, [undefined, {r2j_type, float, []}]},
454 | {specific, [undefined, {list, {specific, [{r2j_type, integer, []}]}}]},
455 | {specific, [undefined, {record, prop_test_rec_inner}]},
456 | {specific, [undefined, {list, {specific, [{record, prop_test_rec_inner}]}}]},
457 | {any, [undefined]},
458 | {any, []},
459 | {specific, [undefined, {list, any}]},
460 | {specific, [undefined, {r2j_type, integer, []}]},
461 | {specific, [undefined, {r2j_type, integer, [-100, 100]}]},
462 | {specific, [undefined, {list, {specific, [{r2j_type, integer, [-100, 100]}]}}]},
463 | {specific, [undefined, {r2j_compile_tests, point, []}]},
464 | {specific, [undefined, null]},
465 | {any, [undefined]},
466 | {specific, [{r2j_type, integer,[]}]}
467 | ],
468 | Zipped = lists:zip(Fields, Types),
469 | ?assertEqual(length(Zipped), length(Got)),
470 | GotZipped = lists:zip(Zipped, Got),
471 | lists:map(fun({Expected, G}) ->
472 | ?assertEqual(Expected, G)
473 | end, GotZipped)
474 | end}
475 |
476 | ].
477 |
478 | proper_test_() ->
479 | Exported = ?MODULE:module_info(exports),
480 | Exported1 = lists:filter(fun
481 | ({Atom, 0}) ->
482 | case atom_to_list(Atom) of
483 | "prop_" ++ _ -> true;
484 | _ -> false
485 | end;
486 | (_) ->
487 | false
488 | end, Exported),
489 | Exported2 = [F || {F, _} <- Exported1],
490 | proper_test_gen(Exported2).
491 |
492 | proper_test_gen([]) ->
493 | {generator, fun() -> [] end};
494 | proper_test_gen([ProperTest | Tail]) ->
495 | {generator, fun() -> [
496 | {atom_to_list(ProperTest), fun() ->
497 | ?assert(proper:quickcheck(erlang:apply(?MODULE, ProperTest, []), 100))
498 | end} |
499 | proper_test_gen(Tail) ]
500 | end}.
501 |
502 | %% proper funcs.
503 | prop_integer() ->
504 | ?FORALL(Val, oneof([int(), real()]),
505 | begin
506 | Expected = #prop_test_rec{prop_integer = Val},
507 | Json = #{prop_integer => Val},
508 | Got = prop_test_rec:from_json(Json),
509 | if
510 | is_integer(Val) ->
511 | {ok, Expected} == Got;
512 | true ->
513 | {ok, Expected, [prop_integer]} == Got
514 | end
515 | end).
516 |
517 | prop_pos_integer() ->
518 | ?FORALL(Int, int(),
519 | begin
520 | Expected = #prop_test_rec{prop_pos_integer = Int},
521 | Json = #{prop_pos_integer => Int},
522 | Got = prop_test_rec:from_json(Json),
523 | if
524 | Int > 0 ->
525 | {ok, Expected} == Got;
526 | true ->
527 | {ok, Expected, [prop_pos_integer]} == Got
528 | end
529 | end).
530 |
531 | prop_int_or_bool() ->
532 | ?FORALL(IntOrBool, oneof([int(), bool(), binary(), real()]),
533 | begin
534 | Expected = #prop_test_rec{prop_int_or_bool = IntOrBool},
535 | Json = #{prop_int_or_bool => IntOrBool},
536 | Got = prop_test_rec:from_json(Json),
537 | case IntOrBool of
538 | X when is_integer(X); is_boolean(X) ->
539 | {ok, Expected} == Got;
540 | _ ->
541 | {ok, Expected, [prop_int_or_bool]} == Got
542 | end
543 | end).
544 |
545 | prop_atoms() ->
546 | ?FORALL(Atom, oneof([init, ready, steady, go, stop, hop]),
547 | begin
548 | Json = #{prop_atoms => list_to_binary(atom_to_list(Atom))},
549 | Got = prop_test_rec:from_json(Json),
550 | case lists:member(Atom, [init, ready, steady]) of
551 | true ->
552 | Expected = #prop_test_rec{prop_atoms = Atom},
553 | {ok, Expected} == Got;
554 | false ->
555 | Expected = #prop_test_rec{prop_atoms = list_to_binary(atom_to_list(Atom))},
556 | {ok, Expected, [prop_atoms]} == Got
557 | end
558 | end).
559 |
560 | prop_non_neg_integer() ->
561 | ?FORALL(Int, int(),
562 | begin
563 | Json = #{prop_non_neg_integer => Int},
564 | Got = prop_test_rec:from_json(Json),
565 | Expected = #prop_test_rec{prop_non_neg_integer = Int},
566 | if
567 | Int < 0 ->
568 | {ok, Expected, [prop_non_neg_integer]} == Got;
569 | true ->
570 | {ok, Expected} == Got
571 | end
572 | end).
573 |
574 | prop_boolean() ->
575 | ?FORALL(Bool, oneof([bool(), goober]),
576 | begin
577 | Expected = #prop_test_rec{prop_boolean = Bool},
578 | Json = #{prop_boolean => Bool},
579 | Got = prop_test_rec:from_json(Json),
580 | if
581 | Bool == goober ->
582 | {ok, Expected,[prop_boolean]} == Got;
583 | true ->
584 | {ok, Expected} == Got
585 | end
586 | end).
587 |
588 | prop_neg_integer() ->
589 | ?FORALL(Int, int(),
590 | begin
591 | Expected = #prop_test_rec{prop_neg_integer = Int},
592 | Json = #{prop_neg_integer => Int},
593 | Got = prop_test_rec:from_json(Json),
594 | if
595 | Int < 0 ->
596 | {ok, Expected} == Got;
597 | true ->
598 | {ok, Expected, [prop_neg_integer]} == Got
599 | end
600 | end).
601 |
602 | prop_number() ->
603 | ?FORALL(Number, oneof([int(), real(), goober]),
604 | begin
605 | Expected = #prop_test_rec{prop_number = Number},
606 | Json = #{prop_number => Number},
607 | Got = prop_test_rec:from_json(Json),
608 | if
609 | is_number(Number) ->
610 | {ok, Expected} == Got;
611 | true ->
612 | {ok, Expected, [prop_number]} == Got
613 | end
614 | end).
615 |
616 | prop_binary() ->
617 | ?FORALL(Binary, oneof([list(int()), binary()]),
618 | begin
619 | Expected = #prop_test_rec{prop_binary = Binary},
620 | Json = #{prop_binary => Binary},
621 | Got = prop_test_rec:from_json(Json),
622 | if
623 | is_binary(Binary) ->
624 | {ok, Expected} == Got;
625 | true ->
626 | {ok, Expected, [prop_binary]} == Got
627 | end
628 | end).
629 |
630 | prop_float() ->
631 | ?FORALL(Float, oneof([int(), real()]),
632 | begin
633 | Expected = #prop_test_rec{prop_float = Float},
634 | Json = #{prop_float => Float},
635 | Got = prop_test_rec:from_json(Json),
636 | if
637 | is_float(Float) ->
638 | {ok, Expected} == Got;
639 | true ->
640 | try Float * 1.0 of
641 | _ ->
642 | {ok, Expected} == Got
643 | catch
644 | error:bararith ->
645 | {ok, Expected, [prop_float]} == Got
646 | end
647 | end
648 | end).
649 |
650 | prop_list_one() ->
651 | ?FORALL(List, list(oneof([int(), real()])),
652 | begin
653 | Expected = #prop_test_rec{prop_list_one = List},
654 | Json = #{prop_list_one => List},
655 | Got = prop_test_rec:from_json(Json),
656 | WarnsFun = fun
657 | (Item, _Ind, Acc) when is_integer(Item) ->
658 | Acc;
659 | (_Item, Ind, Acc) ->
660 | [[prop_list_one, Ind] | Acc]
661 | end,
662 | case fold_ind(WarnsFun, [], List) of
663 | [] ->
664 | {ok, Expected} == Got;
665 | Warns ->
666 | Warns1 = lists:reverse(Warns),
667 | {ok, Expected, Warns1} == Got
668 | end
669 | end).
670 |
671 | prop_record_one() ->
672 | ?FORALL(SubRec, oneof([int(), #{}, #{prop_record_one_inner => oneof([int(), real()])}]),
673 | begin
674 | {Json, Expected, Warns} = case SubRec of
675 | N when is_integer(N) ->
676 | {#{prop_record_one_inner => N}, #prop_test_rec{prop_record_one_inner = N}, [prop_record_one_inner]};
677 | #{f := N} = Obj when is_integer(N) ->
678 | {#{prop_record_one_inner => Obj}, #prop_test_rec{prop_record_one_inner = #prop_test_rec_inner{f = N}}, false};
679 | #{} ->
680 | {#{prop_record_one_inner => #{}}, #prop_test_rec{prop_record_one_inner = #prop_test_rec_inner{f = undefined}}, false};
681 | #{f := N} = Obj ->
682 | {#{prop_record_one_inner => Obj}, #prop_test_rec{prop_record_one_inner = #prop_test_rec_inner{f = N}}, [[prop_record_one_inner, f]]}
683 | end,
684 | Got = prop_test_rec:from_json(Json),
685 | case Warns of
686 | false ->
687 | {ok, Expected} == Got;
688 | _ ->
689 | {ok, Expected, Warns} == Got
690 | end
691 | end).
692 |
693 | prop_user_type() ->
694 | ?FORALL(Val, oneof([<<"bin">>, int(), real()]),
695 | begin
696 | Json = #{<<"prop_user_type">> => Val},
697 | Expected = #prop_test_rec{prop_user_type = Val},
698 | Got = prop_test_rec:from_json(Json),
699 | {ok, Expected} == Got
700 | end).
701 |
702 | prop_user_type_default() ->
703 | ?FORALL(Val, oneof([<<"bin">>, int(), real()]),
704 | begin
705 | Json = #{<<"prop_user_type_default">> => Val},
706 | Expected = #prop_test_rec{prop_user_type_default = Val},
707 | Got = prop_test_rec:from_json(Json),
708 | {ok, Expected} == Got
709 | end).
710 |
711 | prop_user_type_list() ->
712 | ?FORALL(List, list({oneof([<<"a">>,<<"b">>,<<"c">>]), oneof([<<"bin">>, int(), real()])}),
713 | begin
714 | Json = #{<<"prop_user_type_list">> => List},
715 | Expected = #prop_test_rec{prop_user_type_list = List},
716 | Got = prop_test_rec:from_json(Json),
717 | {ok, Expected} == Got
718 | end).
719 |
720 | prop_r2j_integer_type() ->
721 | ?FORALL(Val, oneof([<<"bin">>, int(), real()]),
722 | begin
723 | Json = #{<<"prop_r2j_integer_type">> => Val},
724 | Rec = #prop_test_rec{prop_r2j_integer_type = Val},
725 | Expected = if
726 | is_integer(Val) ->
727 | {ok, Rec};
728 | true ->
729 | {ok, Rec, [prop_r2j_integer_type]}
730 | end,
731 | Trans = fun(J) ->
732 | maps:filter(fun(Key, _) -> Key =:= prop_r2j_integer_type end, J)
733 | end,
734 | Got = prop_test_rec:from_json(Json),
735 | case Got of
736 | Expected ->
737 | try prop_test_rec:to_json(Rec, [Trans]) of
738 | MaybeGood when is_integer(Val) ->
739 | jsx_to_json:to_json(Json,[]) == jsx_to_json:to_json(MaybeGood,[]);
740 | NotGood ->
741 | ?debugFmt("expected a boom due to ~p but got ~p", [Val, NotGood]),
742 | false
743 | catch
744 | error:{badarg, {prop_r2j_integer_type, Val, {specific, [undefined, {r2j_type, integer, []}]}}} when not is_integer(Val) ->
745 | true;
746 | W:Y ->
747 | ?debugFmt("Not the boom I expected: ~p:~p", [W,Y]),
748 | false
749 | end;
750 | _ ->
751 | ?debugFmt("Expected: ~p; got ~p", [Expected, Got])
752 | end
753 | end).
754 |
755 | prop_r2j_integer_min_max_type() ->
756 | ?FORALL(Val, oneof([<<"bin">>, int(), real()]),
757 | begin
758 | Json = #{<<"prop_r2j_integer_min_max_type">> => Val},
759 | Rec = #prop_test_rec{prop_r2j_integer_min_max_type = Val},
760 | Expected = if
761 | is_integer(Val), -100 =< Val, Val =< 100 ->
762 | {ok, Rec};
763 | true ->
764 | {ok, Rec, [prop_r2j_integer_min_max_type]}
765 | end,
766 | Got = prop_test_rec:from_json(Json),
767 | Trans = fun(J) ->
768 | maps:filter(fun(K, _) -> K =:= prop_r2j_integer_min_max_type end, J)
769 | end,
770 | case Got of
771 | Expected ->
772 | try prop_test_rec:to_json(Rec, [Trans]) of
773 | MaybeGood when is_integer(Val), -100 =< Val, Val =< 100 ->
774 | jsx_to_json:to_json(Json,[]) == jsx_to_json:to_json(MaybeGood,[]);
775 | NotGood ->
776 | ?debugFmt("expected a boom due to ~p but got ~p", [Val, NotGood]),
777 | false
778 | catch
779 | error:{badarg, {prop_r2j_integer_min_max_type, Val, {specific, [undefined, {r2j_type, integer, [-100, 100]}]}}} when not is_integer(Val); Val < -100; 100 < Val ->
780 | true;
781 | W:Y ->
782 | ?debugFmt("not the boom I expected: ~p:~p", [W,Y]),
783 | false
784 | end;
785 | _ ->
786 | ?debugFmt("Expected: ~p; got: ~p", [Expected, Got])
787 | end
788 | end).
789 |
790 | prop_r2j_min_max_listed() ->
791 | ?FORALL(Val, list(oneof([<<"bin">>, int(), real()])),
792 | begin
793 | Json = #{<<"prop_r2j_integer_min_max_listed">> => Val},
794 | Rec = #prop_test_rec{prop_r2j_integer_min_max_listed = Val},
795 | FoldFun = fun
796 | (Int, _Index, Acc) when is_integer(Int), -100 =< Int, Int =< 100 ->
797 | Acc;
798 | (_Bad, Index, Acc) ->
799 | [Index | Acc]
800 | end,
801 | Expected = case fold_ind(FoldFun, [], Val) of
802 | [] ->
803 | {ok, Rec};
804 | Warns ->
805 | RevWarns = lists:reverse(Warns),
806 | TaggedWarns = [[prop_r2j_integer_min_max_listed, N] || N <- RevWarns],
807 | {ok, Rec, TaggedWarns}
808 | end,
809 | Got = prop_test_rec:from_json(Json),
810 | IsGoodValue = lists:all(fun(N) ->
811 | is_integer(N) andalso -100 =< N andalso N =< 100
812 | end, Val),
813 | Trans = fun(J) ->
814 | maps:filter(fun(Key,_) -> Key =:= prop_r2j_integer_min_max_listed end, J)
815 | end,
816 | case Got of
817 | Expected ->
818 | try prop_test_rec:to_json(Rec, [Trans]) of
819 | Good when IsGoodValue ->
820 | jsx_to_json:to_json(Json,[]) == jsx_to_json:to_json(Good,[]);
821 | NotGood ->
822 | ?debugFmt("expected a boom due to ~p but got ~p", [Val, NotGood]),
823 | false
824 | catch
825 | error:{badarg, {prop_r2j_integer_min_max_listed, Val, {specific, [undefined, {list, {specific, [{r2j_type, integer, [-100, 100]}]}}]}}} when not IsGoodValue ->
826 | true;
827 | W:Y ->
828 | ?debugFmt("not the boom I was expected: ~p:~p", [W,Y]),
829 | false
830 | end;
831 | _ ->
832 | ?debugFmt("Expected: ~p; got ~p", [Expected, Got]),
833 | false
834 | end
835 | end).
836 |
837 | prop_r2j_type_translation() ->
838 | ?FORALL({X, Y} = RecVal, {int(), int()}, begin
839 | Json = #{<<"type_translation">> => #{<<"x">> => X, <<"y">> => Y}},
840 | Rec = #prop_test_rec{type_translation = RecVal},
841 | Got = prop_test_rec:from_json(Json),
842 | FilterToOnlyTranslation = fun(J) ->
843 | maps:filter(fun(Key, _) -> Key =:= type_translation end, J)
844 | end,
845 | {ok, Rec} == Got andalso jsx_to_json:to_json(Json,[]) == jsx_to_json:to_json(prop_test_rec:to_json(Rec, [FilterToOnlyTranslation]),[])
846 | end).
847 |
848 | fold_ind(Fun, InitAcc, List) ->
849 | {OutAcc, _} = lists:foldl(fun(Elem, {Acc, Ind}) ->
850 | NewAcc = Fun(Elem, Ind, Acc),
851 | {NewAcc, Ind + 1}
852 | end, {InitAcc, 1}, List),
853 | OutAcc.
854 |
855 | point({X,Y}) ->
856 | {ok, #{x => X, y => Y}};
857 |
858 | point(#{<<"x">> := X, <<"y">> := Y}) when is_number(X), is_number(Y) ->
859 | {ok, {X, Y}};
860 |
861 | point(_) ->
862 | error.
863 |
864 |
--------------------------------------------------------------------------------
/test/r2j_compile_tests.hrl:
--------------------------------------------------------------------------------
1 | -type combo() :: integer() | boolean().
2 |
3 | -record(included, {
4 | field
5 | }).
6 |
7 | -record(feature, {
8 | simple,
9 | default = <<"default">>,
10 | integer_type :: integer(),
11 | boolean_type :: boolean(),
12 | binary_type :: binary(),
13 | list_type :: [integer()],
14 | null_type :: 'null',
15 | record_type :: #included{},
16 | default_integer = 42 :: integer(),
17 | int_or_bool :: integer() | boolean(),
18 | over_zero :: pos_integer(),
19 | atoms :: 'init' | 'ready' | 'steady',
20 | int_min_max :: r2j_type:integer(-100, 100),
21 | included_records = [] :: [#included{}]
22 | }).
23 |
--------------------------------------------------------------------------------
/test/r2j_type_tests.erl:
--------------------------------------------------------------------------------
1 | -module(r2j_type_tests).
2 |
3 | -ifdef(TEST).
4 | -include_lib("proper/include/proper.hrl").
5 | -include_lib("eunit/include/eunit.hrl").
6 |
7 | proper_test_() ->
8 | Exported = ?MODULE:module_info(exports),
9 | Exported1 = lists:filter(fun
10 | ({Atom, 0}) ->
11 | case atom_to_list(Atom) of
12 | "prop_" ++ _ -> true;
13 | _ -> false
14 | end;
15 | (_) ->
16 | false
17 | end, Exported),
18 | Exported2 = [F || {F, _} <- Exported1],
19 | proper_test_gen(Exported2).
20 |
21 | proper_test_gen([]) ->
22 | {generator, fun() -> [] end};
23 | proper_test_gen([ProperTest | Tail]) ->
24 | {generator, fun() -> [
25 | {atom_to_list(ProperTest), fun() ->
26 | ?assert(proper:quickcheck(erlang:apply(?MODULE, ProperTest, []), 100))
27 | end} |
28 | proper_test_gen(Tail) ]
29 | end}.
30 |
31 | %% proper funcs.
32 | prop_integer() ->
33 | ?FORALL(Val, oneof([int(), real()]),
34 | begin
35 | Got = r2j_type:integer(Val),
36 | Expected = if
37 | is_integer(Val) ->
38 | {ok, Val};
39 | true ->
40 | error
41 | end,
42 | Expected == Got
43 | end).
44 |
45 | prop_integer_min_max() ->
46 | ?FORALL({Min, Length, Val}, {int(), int(), oneof([int(), real(), <<"bin">>])},
47 | begin
48 | Max = Min + Length,
49 | Expected = if
50 | is_integer(Val) andalso Min =< Val andalso Val =< Max ->
51 | {ok, Val};
52 | true ->
53 | error
54 | end,
55 | Got = r2j_type:integer(Val, Min, Max),
56 | Expected == Got
57 | end).
58 |
59 | prop_string() ->
60 | ?FORALL({Val, MaybeLen}, {binary(), int()},
61 | begin
62 | Len = abs(MaybeLen),
63 | Expected = if
64 | size(Val) =< Len ->
65 | {ok, Val};
66 | true ->
67 | error
68 | end,
69 | Got = r2j_type:string(Val, Len),
70 | Expected == Got
71 | end).
72 |
73 | prop_float() ->
74 | ?FORALL(Val, oneof([int(), real(), <<"bin">>]),
75 | begin
76 | Expected = if
77 | is_binary(Val) ->
78 | error;
79 | true ->
80 | {ok, Val}
81 | end,
82 | Got = r2j_type:float(Val),
83 | Expected == Got
84 | end).
85 |
86 | prop_unsafe_atom() ->
87 | ?FORALL(Val, oneof([<<"bin1">>, <<"bin2">>, 1, 2.0]),
88 | begin
89 | Expected = if
90 | is_binary(Val) ->
91 | {ok, binary_to_atom(Val, utf8)};
92 | true ->
93 | error
94 | end,
95 | Got = r2j_type:unsafe_atom(Val),
96 | Expected == Got
97 | end).
98 |
99 |
100 | -endif.
101 |
--------------------------------------------------------------------------------
/test/rec2json_tests.erl:
--------------------------------------------------------------------------------
1 | -module(rec2json_tests).
2 | -compile([{parse_transform, rec2json}]).
3 |
4 | -ifdef(TEST).
5 | -include_lib("eunit/include/eunit.hrl").
6 |
7 | -record(sub_rec, {
8 | f
9 | }).
10 |
11 | -record(rec2json_tests, {
12 | typed_field = {1} :: rec2json_tests:int_tuple(),
13 | untyped_field = 3,
14 | missing_type = undefined :: nomod:nofun(),
15 | float_field = 1.0 :: float(),
16 | rec_field :: #sub_rec{},
17 | rec_field_list = [] :: [#sub_rec{}]
18 | }).
19 |
20 | -type int_tuple() :: any().
21 | -export_type([int_tuple/0]).
22 | -export([int_tuple/1]).
23 |
24 | int_tuple(Tuple) when is_tuple(Tuple) ->
25 | {ok, tuple_to_list(Tuple)};
26 |
27 | int_tuple(List) when is_list(List) ->
28 | {ok, list_to_tuple(List)};
29 |
30 | int_tuple(_) ->
31 | error.
32 |
33 | feature_test_() -> [
34 |
35 | {"Has correct type info", fun() ->
36 | Types = ?MODULE:field_types(),
37 | ?assertEqual({specific, [{?MODULE, int_tuple, []}]}, proplists:get_value(typed_field, Types)),
38 | ?assertEqual({any, []}, proplists:get_value(untyped_field, Types)),
39 | ?assertEqual({specific, [{nomod, nofun, []}]}, proplists:get_value(missing_type, Types))
40 | end},
41 |
42 | {"does to_json conversion correctly", fun() ->
43 | Rec = #rec2json_tests{typed_field = {2, 3, 4}, untyped_field = <<"hi">>},
44 | Expected = #{typed_field => [2, 3, 4], untyped_field => <<"hi">>, float_field => 1.0, rec_field_list => []},
45 | Got = ?MODULE:to_json(Rec),
46 | ?assertEqual(Expected, Got)
47 | end},
48 |
49 | {"does from_json conversion correctly", fun() ->
50 | Json = #{<<"typed_field">> => [4, 3, 2], <<"untyped_field">> => <<"bye">>},
51 | Expected = #rec2json_tests{typed_field = {4, 3, 2}, untyped_field = <<"bye">>},
52 | Got = ?MODULE:from_json(Json),
53 | ?assertEqual({ok, Expected}, Got)
54 | end},
55 |
56 | {"skips over non-rec2json records", fun() ->
57 | Json = #{rec_field_list => [
58 | #{f => 1},
59 | #{f => 2},
60 | #{f => 3}
61 | ]},
62 | Expected = #rec2json_tests{rec_field_list = [#{f => 1}, #{f => 2}, #{f => 3}]},
63 | % we still get warnings because the type spec of the list does not
64 | % have a valid type that matches the json (like any()).
65 | ExpectedWarnings = [
66 | [rec_field_list, 1],
67 | [rec_field_list, 2],
68 | [rec_field_list, 3]
69 | ],
70 | Got = ?MODULE:from_json(Json),
71 | ?assertEqual({ok, Expected, ExpectedWarnings}, Got)
72 | end},
73 |
74 | {"if a field is skipped, don't bother to verify it's type", fun() ->
75 | Record = #rec2json_tests{rec_field_list = {not_valid}},
76 | Expected = #{typed_field => [1], untyped_field => 3, float_field => 1.0},
77 | Got = ?MODULE:to_json([rec_field_list], Record),
78 | ?assertEqual(Expected, Got)
79 | end},
80 |
81 | {"can to_json with types loads needed module", fun() ->
82 | code:delete(r2j_type),
83 | code:purge(r2j_type),
84 | false = code:is_loaded(r2j_type),
85 | Rec = #?MODULE{},
86 | Got = ?MODULE:to_json(Rec),
87 | ?assertEqual(1.0, maps:get(float_field, Got))
88 | end}
89 |
90 | ].
91 |
92 | -endif.
93 |
--------------------------------------------------------------------------------
/test/renamed_property.erl:
--------------------------------------------------------------------------------
1 | -module(renamed_property).
2 | -compile({parse_transform, rec2json}).
3 | -rec2json({type_name, goober}).
4 |
5 | -record(renamed_property, {
6 | f1 = 42 :: pos_integer(),
7 | f2 = hello :: hello | hi | yo | hey
8 | }).
9 |
--------------------------------------------------------------------------------
/test/suppress_property.erl:
--------------------------------------------------------------------------------
1 | -module(suppress_property).
2 | -compile({parse_transform, rec2json}).
3 | -rec2json([{generate_type, false}]).
4 |
5 | -record(suppress_property, {
6 | f1 = <<"hello">> :: binary(),
7 | f2 = 7 :: number()
8 | }).
9 |
--------------------------------------------------------------------------------
/test/test_person.erl:
--------------------------------------------------------------------------------
1 | -module(test_person).
2 |
3 | -compile([{parse_transform, rec2json}]).
4 |
5 | -include("../test/test_rec.hrl").
6 |
7 | -export([is_married/1]).
8 |
9 | is_married(#test_person{spouse_id = undefined}) ->
10 | false;
11 | is_married(_) ->
12 | true.
--------------------------------------------------------------------------------
/test/test_rec.erl:
--------------------------------------------------------------------------------
1 | -module(test_rec).
2 |
3 | -compile([{parse_transform, rec2json}]).
4 |
5 | -include("../test/test_rec.hrl").
6 |
--------------------------------------------------------------------------------
/test/test_rec.hrl:
--------------------------------------------------------------------------------
1 | -record(test_rec, {
2 | id,
3 | name :: binary(),
4 | counter = 1
5 | }).
6 |
7 | -record(test_person, {
8 | id :: pos_integer(),
9 | name = <<"gustav">> :: binary(),
10 | age = 0 :: non_neg_integer(),
11 | spouse_id :: pos_integer()
12 | }).
13 |
14 |
--------------------------------------------------------------------------------