├── .gitignore
├── LICENSE
├── Makefile
├── README.md
├── examples
├── .gitignore
├── example1.c
├── example2.c
└── json
│ └── example1.json
├── tanto.h
└── tests
├── .gitignore
├── acutest.h
├── sample_01.json
├── sample_02.json
└── tanto_unittest.c
/.gitignore:
--------------------------------------------------------------------------------
1 | tanto
2 | json/*
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | CC = cc
2 | CFLAGS = -Wall -Wextra -pedantic
3 |
4 | example:
5 | mkdir -p examples/bin
6 | $(CC) $(CFLAGS) -o examples/bin/example1 examples/example1.c
7 | $(CC) $(CFLAGS) -o examples/bin/example2 examples/example2.c
8 |
9 | clean:
10 | rm -rf examples/bin
11 | rm -rf bin
12 | rm -rf tests/result
13 |
14 | test:
15 | mkdir -p tests/result
16 | $(CC) $(CFLAGS) -o tests/result/tanto_unittest tests/tanto_unittest.c
17 | ./tests/result/tanto_unittest -v
18 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # json parser and creator library in C, under development, not ready to use!
2 |
3 | > tanto.h
4 |
5 | # Using tanto
6 | To use tanto you can include tanto.h header file.
7 |
8 | ```
9 | #include "tanto.h"
10 | ```
11 |
12 | # typedef in tanto.h
13 | ```
14 | TJSON_t *json;
15 | ```
16 |
17 | # example usage
18 | ```
19 | TJSON_t *json = NULL;
20 | TANTO_INIT(&json);
21 |
22 |
23 | TJSON_t *server = tanto_create_node(TANTO_JSON_OBJECT, "server", NULL);
24 | tanto_push(&json, server);
25 |
26 | TJSON_t *path = tanto_create_node(TANTO_JSON_OBJECT_FIELD, "path", "http://www.gnu.org/licenses/");
27 | tanto_push(&json, path);
28 |
29 |
30 | TJSON_t *parser = tanto_create_node(TANTO_JSON_OBJECT_FIELD, "parser", "tanto");
31 | TJSON_t *library = tanto_create_node(TANTO_JSON_OBJECT, "library", NULL);
32 | TJSON_t *lex = tanto_create_node(TANTO_JSON_OBJECT_FIELD, "lex", "lexer");
33 | tanto_push(&json, parser);
34 | tanto_push(&server, library);
35 | tanto_push(&server, lex);
36 |
37 | TJSON_t *usage = tanto_create_node(TANTO_JSON_OBJECT_FIELD ,"usage", "example.c");
38 | TJSON_t *tests = tanto_create_node(TANTO_JSON_OBJECT_FIELD ,"tests", "test.c");
39 | tanto_push(&library, usage);
40 | tanto_push(&library, tests);
41 |
42 |
43 | TJSON_t *color = tanto_create_node(TANTO_JSON_OBJECT_FIELD, "color", "red");
44 | tanto_push(&json, color);
45 |
46 | TJSON_t *main = tanto_create_node(TANTO_JSON_OBJECT_FIELD ,"main", "main.c");
47 | tanto_push(&json, main);
48 |
49 |
50 | TJSON_t *functions = tanto_create_node(TANTO_JSON_ARRAY, "functions", NULL);
51 | tanto_push(&json, functions);
52 | TJSON_t *pop = tanto_create_node(TANTO_JSON_OBJECT_FIELD ,"pop", NULL);
53 | tanto_push(&functions, pop);
54 | TJSON_t *push = tanto_create_node(TANTO_JSON_OBJECT_FIELD ,"push", NULL);
55 | tanto_push(&functions, push);
56 |
57 | tanto_write_file("../json/example2-output.json", json);
58 | ```
59 |
60 | ## make examples
61 |
62 | ```
63 | $ make example
64 | ````
65 |
66 | ```
67 | $ ./example1
68 | $ ./example2
69 | ````
70 |
--------------------------------------------------------------------------------
/examples/.gitignore:
--------------------------------------------------------------------------------
1 | bin/
--------------------------------------------------------------------------------
/examples/example1.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This program is free software; you can redistribute it and/or modify it
3 | * under the terms and conditions of the GNU General Public License,
4 | * version 2, as published by the Free Software Foundation.
5 | *
6 | * This program is distributed in the hope it will be useful, but WITHOUT
7 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
8 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
9 | * more details.
10 | *
11 | * You should have received a copy of the GNU General Public License
12 | * along with this program. If not, see .
13 | */
14 |
15 | #include "../tanto.h"
16 |
17 | /*
18 | * read jsno file, parse and print
19 | */
20 | int main()
21 | {
22 | char *json_file = "simple.json";
23 | char *stream = NULL;
24 |
25 | stream = tjson_read_file(json_file);
26 |
27 | //TJSON_t *json = NULL;
28 | //TJSON_INIT(&json);
29 |
30 | int error;
31 | if ((error = __tjson_lex(stream)) > 0)
32 | printf("%s %s %s: %d\n", "ERROR! while parsing file", json_file, "line", error);
33 | //else
34 | // tjson_print(json);
35 |
36 |
37 | //if (json != NULL) tjson_erase(&json);
38 | if (stream != NULL) free(stream);
39 |
40 |
41 | return 0;
42 | }
43 |
--------------------------------------------------------------------------------
/examples/example2.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This program is free software; you can redistribute it and/or modify it
3 | * under the terms and conditions of the GNU General Public License,
4 | * version 2, as published by the Free Software Foundation.
5 | *
6 | * This program is distributed in the hope it will be useful, but WITHOUT
7 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
8 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
9 | * more details.
10 | *
11 | * You should have received a copy of the GNU General Public License
12 | * along with this program. If not, see .
13 | */
14 |
15 | #include "../tanto.h"
16 |
17 | /*
18 | * create this json object and print on stdout or file.
19 | *
20 | {
21 | "functions": [
22 | {
23 | "delete2": "iterative",
24 | "delete1": "recursive"
25 | },
26 | "push",
27 | "pop"
28 | ],
29 | "main": "main.c",
30 | "color": "red",
31 | "order": 63928.120,
32 | "parser": "tanto",
33 | "path": "http://www.gnu.org/licenses/",
34 | "server": {
35 | "lex": "lexer",
36 | "library": {
37 | "address": null,
38 | "support": true,
39 | "test": "test.c",
40 | "usage": "example.c"
41 | }
42 | }
43 | }
44 | */
45 |
46 |
47 |
48 | /*
49 | * create json, add field, and print
50 | */
51 | int main()
52 | {
53 | TJSON_t *json = NULL;
54 | TJSON_INIT(&json);
55 |
56 |
57 | TJSON_t *server = tjson_create_node_object("server");
58 | TJSON_t *path = tjson_create_node_string("path", "http://www.gnu.org/licenses/");
59 | tjson_push(&json, server);
60 | tjson_push(&json, path);
61 |
62 |
63 | TJSON_t *parser = tjson_create_node_string("parser", "tanto");
64 | TJSON_t *order = tjson_create_node_number("order", 63928.12);
65 | TJSON_t *library = tjson_create_node_object("library");
66 | TJSON_t *lex = tjson_create_node_string("lex", "lexer");
67 | tjson_push(&json, parser);
68 | tjson_push(&json, order);
69 | tjson_push(&server, library);
70 | tjson_push(&server, lex);
71 |
72 | TJSON_t *usage = tjson_create_node_string("usage", "example.c");
73 | TJSON_t *test = tjson_create_node_string("test", "test.c");
74 | TJSON_t *support = tjson_create_node_bool("support", true);
75 | TJSON_t *address = tjson_create_node_null("address");
76 | tjson_push(&library, usage);
77 | tjson_push(&library, test);
78 | tjson_push(&library, support);
79 | tjson_push(&library, address);
80 |
81 |
82 | TJSON_t *color = tjson_create_node_string("color", "red");
83 | TJSON_t *main = tjson_create_node_string("main", "main.c");
84 | tjson_push(&json, color);
85 | tjson_push(&json, main);
86 |
87 |
88 | TJSON_t *functions = tjson_create_node_array("functions");
89 | tjson_push(&json, functions);
90 |
91 | TJSON_t *pop = tjson_create_node_string(NULL, "pop");
92 | TJSON_t *push = tjson_create_node_string(NULL, "push");
93 | TJSON_t *delete = tjson_create_node_object(NULL);
94 | tjson_push(&functions, pop);
95 | tjson_push(&functions, push);
96 | tjson_push(&functions, delete);
97 |
98 | TJSON_t *delete1 = tjson_create_node_string("delete1", "recursive");
99 | TJSON_t *delete2 = tjson_create_node_string("delete2", "iterative");
100 | tjson_push(&delete, delete1);
101 | tjson_push(&delete, delete2);
102 |
103 |
104 | tjson_print(json);
105 | //tjson_write_file("../json/example2-output.json", json);
106 |
107 | if (json != NULL) tjson_erase(&json);
108 |
109 | return 0;
110 | }
111 |
--------------------------------------------------------------------------------
/examples/json/example1.json:
--------------------------------------------------------------------------------
1 | {
2 | "products": [
3 | {
4 | "_id": {
5 | "$oid": "5968dd23fc13ae04d9000001"
6 | },
7 | "product_name": "sildenafil citrate",
8 | "supplier": "Wisozk Inc",
9 | "quantity": 261,
10 | "unit_cost": "$10.47"
11 | },
12 | {
13 | "_id": {
14 | "$oid": "5968dd23fc13ae04d9000002"
15 | },
16 | "product_name": "Mountain Juniperus ashei",
17 | "supplier": "Keebler-Hilpert",
18 | "quantity": 292,
19 | "unit_cost": "$8.74"
20 | },
21 | {
22 | "_id": {
23 | "$oid": "5968dd23fc13ae04d9000003"
24 | },
25 | "product_name": "Dextromathorphan HBr",
26 | "supplier": "Schmitt-Weissnat",
27 | "quantity": 211,
28 | "unit_cost": "$20.53"
29 | }
30 | ]
31 | }
32 |
--------------------------------------------------------------------------------
/tanto.h:
--------------------------------------------------------------------------------
1 | #ifndef __TANTO_H
2 | #define __TANTO_H
3 |
4 | //added at git practice workshop
5 |
6 | /*
7 | * This program is free software; you can redistribute it and/or modify it
8 | * under the terms and conditions of the GNU General Public License,
9 | * version 2, as published by the Free Software Foundation.
10 | *
11 | * This program is distributed in the hope it will be useful, but WITHOUT
12 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 | * more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with this program. If not, see .
18 | */
19 |
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 |
26 | #define _LIBRARY_NAME "tanto"
27 | #define _LIBRARY_DESC "json parser and creator library in C"
28 | #define _LIBRARY_AUTHORS "msoodb (Masoud Bolhassani), adavari (Alireza Davari)"
29 | #define _LIBRARY_VERSION "0.0.1"
30 | #define _LIBRARY_URL "https://msoodb.org/tanto"
31 |
32 |
33 | #define TJSON_INIT(json) __tjson_init((json));
34 |
35 |
36 | #define TJSON_STRING 0
37 | #define TJSON_NUMBER 1
38 | #define TJSON_OBJECT 2
39 | #define TJSON_ARRAY 3
40 | #define TJSON_BOOL 4
41 | #define TJSON_NULL 5
42 |
43 |
44 | #define TJSON_IN_WHITE_SPACE -1
45 | #define TJSON_IN_STRING 0
46 | #define TJSON_IN_ESCAPE_CHAR 1
47 | #define TJSON_IN_IDENTIFIER 2
48 |
49 | const char *__tjson_keyword[] = {
50 | "true",
51 | "false",
52 | "null"
53 | };
54 |
55 | enum TJSON_TOKEN_TYPE {
56 | TJSON_TOKEN_PUNCTUATOR,
57 | TJSON_TOKEN_STRING,
58 | TJSON_TOKEN_IDENTIFIER,
59 | TJSON_TOKEN_NUMBER,
60 | TJSON_TOKEN_KEYWORD
61 | };
62 |
63 | typedef struct __json
64 | {
65 | struct __json *child;
66 | struct __json *next;
67 | char *key;
68 | int v_type;
69 |
70 | char *v_string;
71 | double v_number;
72 | bool v_bool;
73 |
74 | } TJSON_t;
75 |
76 | typedef struct __stack
77 | {
78 | enum TJSON_TOKEN_TYPE type;
79 | char *data;
80 | struct __stack *next;
81 | } TSTACK_t;
82 |
83 |
84 | typedef struct __stack_node
85 | {
86 | TJSON_t *data;
87 | struct __stack_node *next;
88 | } S_NODE_t;
89 |
90 |
91 | void __tjson_erase_node(TJSON_t **node)
92 | {
93 | if (*node == NULL) return;
94 |
95 | if ((*node)->key != NULL) free((*node)->key);
96 | if ((*node)->v_string != NULL) free((*node)->v_string);
97 |
98 | free(*node);
99 | }
100 |
101 | void tjson_erase(TJSON_t **json)
102 | {
103 | TJSON_t *current = *json;
104 |
105 | while (*json) {
106 | if ((*json)->child != NULL) {
107 | tjson_erase(&(*json)->child);
108 | }
109 |
110 | current = *json;
111 | *json = (*json)->next;
112 |
113 | __tjson_erase_node(¤t);
114 | }
115 | }
116 |
117 | void __tstack_push(TSTACK_t **stack, enum TJSON_TOKEN_TYPE type, char *data)
118 | {
119 | TSTACK_t *node = (TSTACK_t *)malloc(sizeof(TSTACK_t));
120 | if (node == NULL) return;
121 |
122 | node->type = type;
123 | node->data = data;
124 | node->next = (*stack);
125 |
126 | (*stack) = node;
127 | }
128 |
129 | TSTACK_t *__tstack_pop(TSTACK_t **stack)
130 | {
131 | TSTACK_t *top;
132 | if (*stack == NULL) return NULL;
133 |
134 | top = *stack;
135 | *stack = top->next;
136 |
137 | return top;
138 | }
139 |
140 | void __tstack_print(TSTACK_t **stack)
141 | {
142 | TSTACK_t *node;
143 | char *str_type;
144 |
145 | printf("number\ttype\t\tvalue\n");
146 | printf("----------------------------------------\n");
147 |
148 | int i = 0;
149 | while (*stack != NULL) {
150 |
151 | node = __tstack_pop(stack);
152 | if (node == NULL || node->data == NULL) {
153 | printf("%d\t%s\t\t%s\n", ++i, "!!!!ERROR!!!!", "!!!!ERROR!!!!");
154 | return;
155 | }
156 |
157 | switch (node->type) {
158 | case TJSON_TOKEN_PUNCTUATOR:
159 | str_type = "TJSON_TOKEN_PUNCTUATOR";
160 | break;
161 | case TJSON_TOKEN_STRING:
162 | str_type = "TJSON_TOKEN_STRING";
163 | break;
164 | case TJSON_TOKEN_IDENTIFIER:
165 | str_type = "TJSON_TOKEN_IDENTIFIER";
166 | break;
167 | default:
168 | str_type = "!!!!ERROR!!!!";
169 | break;
170 | }
171 |
172 | printf("%d\t%s\t\t%s\n", ++i, str_type, node->data);
173 |
174 | if (node != NULL && node->data != NULL) free(node->data);
175 | if (node != NULL) free(node);
176 |
177 | node = NULL;
178 | }
179 | if (node != NULL) free(node);
180 | }
181 |
182 | void __stack_push(S_NODE_t **stack, TJSON_t *data)
183 | {
184 | S_NODE_t *node = (S_NODE_t *)malloc(sizeof(S_NODE_t));
185 | if (node == NULL) return;
186 |
187 | node->data = data;
188 | node->next = (*stack);
189 |
190 | (*stack) = node;
191 | }
192 |
193 | TJSON_t *__stack_pop(S_NODE_t **stack)
194 | {
195 | TJSON_t *data;
196 | S_NODE_t *top;
197 | if (*stack == NULL) return 0;
198 |
199 | top = *stack;
200 | data = top->data;
201 | *stack = top->next;
202 |
203 | free(top);
204 |
205 | return data;
206 | }
207 |
208 | void __stack_print(S_NODE_t *stack)
209 | {
210 | while (stack != NULL) {
211 | printf("%8p\n", (void *)stack);
212 | stack = stack->next;
213 | }
214 | }
215 |
216 | TJSON_t *__tjson_create_node_empty(char *key, int v_type)
217 | {
218 | TJSON_t *node = (TJSON_t*) malloc(sizeof(TJSON_t) * 1);
219 | if (node == NULL) return NULL;
220 |
221 |
222 | node->child = NULL;
223 | node->next = NULL;
224 | node->key = NULL;
225 | node->v_type = v_type;
226 |
227 | node->v_string = NULL;
228 | node->v_number = 0;
229 | node->v_bool = false;
230 |
231 |
232 | if (key != NULL) {
233 | size_t z;
234 | z = strlen(key);
235 | node->key = (char *)malloc(sizeof(char) * (z+1));
236 | memcpy(node->key, key, z);
237 | node->key[z] = '\0';
238 | }
239 |
240 | return node;
241 | }
242 |
243 | TJSON_t *tjson_create_node_string(char *key, char *v_string)
244 | {
245 | TJSON_t *node = __tjson_create_node_empty(key, TJSON_STRING);
246 | if (node == NULL) return NULL;
247 |
248 | if (v_string != NULL) {
249 | size_t z;
250 | z = strlen(v_string);
251 | node->v_string = (char *)malloc(sizeof(char) * (z+1));
252 | memcpy(node->v_string, v_string, z);
253 | node->v_string[z] = '\0';
254 | }
255 |
256 | return node;
257 | }
258 |
259 | TJSON_t *tjson_create_node_number(char *key, double v_number)
260 | {
261 | TJSON_t *node = __tjson_create_node_empty(key, TJSON_NUMBER);
262 | if (node == NULL) return NULL;
263 | node->v_number = v_number;
264 |
265 | return node;
266 | }
267 |
268 | TJSON_t *tjson_create_node_object(char *key)
269 | {
270 | TJSON_t *node = __tjson_create_node_empty(key, TJSON_OBJECT);
271 | if (node == NULL) return NULL;
272 |
273 | return node;
274 | }
275 |
276 | TJSON_t *tjson_create_node_array(char *key)
277 | {
278 | TJSON_t *node = __tjson_create_node_empty(key, TJSON_ARRAY);
279 | if (node == NULL) return NULL;
280 |
281 | return node;
282 | }
283 |
284 | TJSON_t *tjson_create_node_bool(char *key, bool v_bool)
285 | {
286 | TJSON_t *node = __tjson_create_node_empty(key, TJSON_BOOL);
287 | if (node == NULL) return NULL;
288 |
289 | node->v_bool = v_bool;
290 | return node;
291 | }
292 |
293 | TJSON_t *tjson_create_node_null(char *key)
294 | {
295 | TJSON_t *node = __tjson_create_node_empty(key, TJSON_NULL);
296 | if (node == NULL) return NULL;
297 |
298 | return node;
299 | }
300 |
301 | void __tjson_init(TJSON_t **json)
302 | {
303 | TJSON_t *node = __tjson_create_node_empty(NULL, TJSON_OBJECT);
304 | if (node == NULL) return;
305 |
306 | *json = node;
307 | }
308 |
309 | void tjson_push(TJSON_t **json, TJSON_t *node)
310 | {
311 | node->next = (*json)->child;
312 | (*json)->child = node;
313 | }
314 |
315 | TJSON_t *tjson_pop(TJSON_t **json)
316 | {
317 | if (*json == NULL) return NULL;
318 |
319 | TJSON_t *current = *json;
320 | *json = (*json)->next;
321 |
322 | return current;
323 | }
324 |
325 | TJSON_t *tjson_find(TJSON_t *json, char *key)
326 | {
327 | if (json == NULL || json->child == NULL)
328 | return NULL;
329 |
330 | json = json->child;
331 |
332 | while (json != NULL) {
333 | if (strcmp(json->key, key) == 0) return json;
334 | json = json->next;
335 | }
336 |
337 | return NULL;
338 | }
339 |
340 | void __tjson_print(TJSON_t *json, FILE *fp, int type, int level)
341 | {
342 | int comma;
343 | comma = 0;
344 |
345 | if (level < 1) level = 1;
346 |
347 | char start, end;
348 | start = '{';
349 | end = '}';
350 |
351 | if (type == TJSON_ARRAY){
352 | start = '[';
353 | end = ']';
354 | }
355 |
356 | fprintf(fp, "%c\n", start);
357 | while (json != NULL) {
358 | if (comma) fprintf(fp, "%c\n", ',');
359 |
360 | fprintf(fp, "%*s", level*2, "");
361 |
362 | if (json->key != NULL) {
363 | fprintf(fp, "\"%s\"", json->key);
364 | if (type != TJSON_ARRAY) fprintf(fp, ": " );
365 | }
366 |
367 | switch (json->v_type) {
368 | case TJSON_STRING:
369 | if (json->v_string != NULL)
370 | fprintf(fp, "\"%s\"", json->v_string);
371 | else
372 | fprintf(fp, "\"%s\"", "");
373 | break;
374 | case TJSON_NUMBER:
375 | fprintf(fp, "%.3lf", json->v_number);
376 | break;
377 | case TJSON_BOOL:
378 | if (json->v_bool == true) fprintf(fp, "%s", "true");
379 | else if (json->v_bool == false) fprintf(fp, "%s", "false");
380 | break;
381 | case TJSON_NULL:
382 | fprintf(fp, "%s", "null");
383 | break;
384 | default:
385 | break;
386 | }
387 |
388 | comma = 1;
389 |
390 | if ((json->v_type == TJSON_OBJECT) ||
391 | (json->v_type == TJSON_ARRAY)) {
392 | __tjson_print(json->child, fp, json->v_type, level+1);
393 | }
394 |
395 | json = json->next;
396 | }
397 | fprintf(fp, "\n%*s%c", (level-1)*2, "", end);
398 | if (level == 1) fprintf(fp, "\n");
399 | }
400 |
401 | void tjson_print(TJSON_t *json)
402 | {
403 | if (json == NULL) return;
404 | __tjson_print(json->child, stdout, json->v_type, 1);
405 | }
406 |
407 | void __tjson_print_addr(TJSON_t *json)
408 | {
409 | while (json != NULL) {
410 |
411 | printf("\t%s\n", " --------------------");
412 | printf("%8p", (void *)json);
413 | printf("%s", " | ");
414 | printf("%8p %s", (void *)json->next, "|");
415 | printf("%8p %s\n", (void *)json->child, "|");
416 | printf("\t%s\n\n", " --------------------");
417 | __tjson_print_addr(json->child);
418 |
419 | json = json->next;
420 | }
421 | }
422 |
423 | void __append_char(char **token, char *c)
424 | {
425 | if (*token == NULL) {
426 | *token = (char *)malloc(sizeof(char));
427 | **token = '\0';
428 | }
429 |
430 | size_t token_size = strlen(*token);
431 |
432 | *token = (char *)realloc(*token, (token_size + 2) * sizeof(char));
433 | strncat(*token, c, 1);
434 | }
435 |
436 | int __tjson_lex(const char *stream)
437 | {
438 | TSTACK_t *stack;
439 | enum TJSON_TOKEN_TYPE token_type;
440 | char *token;
441 | bool is_dirty;
442 | bool touch_delimitor;
443 | int status;
444 | int line_number;
445 |
446 | stack = NULL;
447 | token_type = TJSON_TOKEN_STRING;
448 | token = NULL;
449 | is_dirty = false;
450 | touch_delimitor = false;
451 | status = TJSON_IN_WHITE_SPACE;
452 | line_number = 1;
453 |
454 | char c;
455 | while ((c = *stream++) != '\0') {
456 |
457 | switch (c) {
458 | case ' ':
459 | switch (status) {
460 | case TJSON_IN_STRING:
461 | __append_char(&token, &c);
462 | break;
463 | default:
464 | if (is_dirty) touch_delimitor = true;
465 | status = TJSON_IN_WHITE_SPACE;
466 | break;
467 | }
468 | break;
469 | case '\t':
470 | case '\n':
471 | switch (status) {
472 | case TJSON_IN_STRING:
473 | __append_char(&token, &c);
474 | break;
475 | default:
476 | if (is_dirty) touch_delimitor = true;
477 | status = TJSON_IN_WHITE_SPACE;
478 | break;
479 | }
480 | line_number++;
481 | break;
482 | case '"':
483 | switch (status) {
484 | case TJSON_IN_STRING:
485 | touch_delimitor = true;
486 | break;
487 | case TJSON_IN_ESCAPE_CHAR:
488 | status = TJSON_IN_STRING;
489 | break;
490 | case TJSON_IN_WHITE_SPACE:
491 | status = TJSON_IN_STRING;
492 | is_dirty = true;
493 | break;
494 | default:
495 | break;
496 | }
497 | token_type = TJSON_TOKEN_STRING;
498 | __append_char(&token, &c);
499 | break;
500 | case '\\':
501 | switch (status) {
502 | case TJSON_IN_STRING:
503 | status = TJSON_IN_ESCAPE_CHAR;
504 | break;
505 | case TJSON_IN_ESCAPE_CHAR:
506 | status = TJSON_IN_STRING;
507 | break;
508 | default:
509 | break;
510 | }
511 | __append_char(&token, &c);
512 | break;
513 | case '{':
514 | case '[':
515 | case ']':
516 | case '}':
517 | case ':':
518 | case ',':
519 | switch (status) {
520 | case TJSON_IN_STRING:
521 | __append_char(&token, &c);
522 | break;
523 | case TJSON_IN_ESCAPE_CHAR:
524 | return line_number;
525 | default:
526 | touch_delimitor = true;
527 | break;
528 | }
529 | break;
530 | default:
531 | switch (status) {
532 | case TJSON_IN_STRING:
533 | break;
534 | case TJSON_IN_ESCAPE_CHAR:
535 | switch (c) {
536 | case 'b':
537 | case 'f':
538 | case 'n':
539 | case 'r':
540 | case 't':
541 | status = TJSON_IN_STRING;
542 | break;
543 | default:
544 | return line_number;
545 | }
546 | break;
547 | case TJSON_IN_WHITE_SPACE:
548 | token = NULL;
549 | is_dirty = true;
550 | status = TJSON_IN_IDENTIFIER;
551 | token_type = TJSON_TOKEN_IDENTIFIER;
552 | break;
553 | default:
554 | break;
555 | }
556 | __append_char(&token, &c);
557 | break;
558 | }
559 |
560 | if (touch_delimitor) {
561 | if (is_dirty) {
562 | __tstack_push(&stack, token_type, token);
563 | token = NULL;
564 | }
565 | if (!isspace(c) && c != '"') {
566 | __append_char(&token, &c);
567 | __tstack_push(&stack, TJSON_TOKEN_PUNCTUATOR, token);
568 | }
569 |
570 | is_dirty = false;
571 | touch_delimitor = false;
572 |
573 | token = NULL;
574 | status = TJSON_IN_WHITE_SPACE;
575 | }
576 | }
577 |
578 | __tstack_print(&stack);
579 |
580 | if (stack != NULL) free(stack);
581 | if (token != NULL) free(token);
582 |
583 | return 0;
584 | }
585 |
586 | #ifdef __IGNORE_
587 | int tjson_lex(TJSON_t **json, const char *stream)
588 | {
589 | if (stream == NULL) return -1;
590 |
591 | S_NODE_t *stack;
592 | TJSON_t *current, *new;
593 | stack = NULL;
594 | current = new = NULL;
595 |
596 | char *token;
597 | size_t token_size;
598 | int status;
599 | token = NULL;
600 | token_size = 1;
601 | status = TJSON_OUT_OF_TOKEN;
602 |
603 | char *first, *second;
604 | first = second = NULL;
605 |
606 | double v_number;
607 | bool v_bool;
608 | v_number = 0;
609 | v_bool = false;
610 |
611 |
612 | int line_number;
613 |
614 | // flages
615 | bool is_dirty, save;
616 | int token_type;
617 | int end_of_object_f, end_of_array_f;
618 | int escape_char_status;
619 |
620 | is_dirty = save = false;
621 | token_type = TJSON_STRING;
622 | end_of_object_f = end_of_array_f = 0;
623 | escape_char_status = TJSON_OUT_OF_ESCAPE_CHAR;
624 |
625 |
626 | while(isspace((unsigned char)*stream)) stream++;
627 | if (*stream != '{') return -1;
628 |
629 | stream++;
630 | current = *json;
631 |
632 |
633 | line_number = 1;
634 |
635 | char c;
636 | do {
637 | c = *stream++;
638 |
639 | switch (c) {
640 | case ' ':
641 | switch (status) {
642 | case TJSON_IN_STRING_TOKEN:
643 | __append_char(&token, ++token_size, &c);
644 | break;
645 | default:
646 | if (is_dirty) return line_number;
647 | status = TJSON_OUT_OF_TOKEN;
648 | break;
649 | }
650 | break;
651 | case '\n':
652 | switch (status) {
653 | case TJSON_IN_STRING_TOKEN:
654 | __append_char(&token, ++token_size, &c);
655 | break;
656 | default:
657 | break;
658 | }
659 | line_number++;
660 | break;
661 | case '"':
662 | switch (status) {
663 | case TJSON_IN_STRING_TOKEN:
664 | if (escape_char_status == TJSON_IN_ESCAPE_CHAR) {
665 | __append_char(&token, ++token_size, &c);
666 | escape_char_status = TJSON_OUT_OF_ESCAPE_CHAR;
667 | }else {
668 | token_type = TJSON_STRING;
669 | status = TJSON_OUT_OF_TOKEN;
670 | }
671 | break;
672 | case TJSON_OUT_OF_TOKEN:
673 | token = NULL;
674 | token_size = 1;
675 | status = TJSON_IN_STRING_TOKEN;
676 | token_type = TJSON_STRING;
677 | is_dirty = true;
678 | break;
679 | default:
680 | return line_number;
681 | }
682 | break;
683 | case '\\':
684 | switch (status) {
685 | case TJSON_IN_STRING_TOKEN:
686 | if (escape_char_status == TJSON_OUT_OF_ESCAPE_CHAR) {
687 | escape_char_status = TJSON_IN_ESCAPE_CHAR;
688 | }else {
689 | escape_char_status = TJSON_OUT_OF_ESCAPE_CHAR;
690 | }
691 | __append_char(&token, ++token_size, &c);
692 | break;
693 | default:
694 | return line_number;
695 | }
696 | break;
697 | case '{':
698 | switch (status) {
699 | case TJSON_IN_STRING_TOKEN:
700 | __append_char(&token, ++token_size, &c);
701 | break;
702 | default:
703 | status = TJSON_OUT_OF_TOKEN;
704 | token_type = TJSON_OBJECT;
705 | second = NULL;
706 | save = is_dirty = true;
707 | break;
708 | }
709 | break;
710 | case '[':
711 | switch (status) {
712 | case TJSON_IN_STRING_TOKEN:
713 | __append_char(&token, ++token_size, &c);
714 | break;
715 | default:
716 | status = TJSON_OUT_OF_TOKEN;
717 | token_type = TJSON_ARRAY;
718 | second = NULL;
719 | save = is_dirty = true;
720 | break;
721 | }
722 | break;
723 | case ']':
724 | switch (status) {
725 | case TJSON_IN_STRING_TOKEN:
726 | __append_char(&token, ++token_size, &c);
727 | break;
728 | default:
729 | second = (char *)malloc(sizeof(char) * token_size);
730 | if (token != NULL) {
731 | strncpy(second, token, token_size);
732 | }else {
733 | second = NULL;
734 | }
735 | status = TJSON_OUT_OF_TOKEN;
736 | end_of_array_f = true;
737 | save = is_dirty;
738 | break;
739 | }
740 | break;
741 | case '}':
742 | switch (status) {
743 | case TJSON_IN_STRING_TOKEN:
744 | __append_char(&token, ++token_size, &c);
745 | break;
746 | default:
747 | second = (char *)malloc(sizeof(char) * token_size);
748 | if (token != NULL) {
749 | strncpy(second, token, token_size);
750 | }else {
751 | second = NULL;
752 | }
753 | status = TJSON_OUT_OF_TOKEN;
754 | end_of_object_f = true;
755 | save = is_dirty;
756 | break;
757 | }
758 | break;
759 | case ':':
760 | switch (status) {
761 | case TJSON_IN_STRING_TOKEN:
762 | __append_char(&token, ++token_size, &c);
763 | break;
764 | default:
765 | first = (char *)malloc(sizeof(char) * token_size);
766 | strncpy(first, token, token_size);
767 | status = TJSON_OUT_OF_TOKEN;
768 | break;
769 | }
770 | break;
771 | case '\0':
772 | break;
773 | case ',':
774 | switch (status) {
775 | case TJSON_IN_STRING_TOKEN:
776 | __append_char(&token, ++token_size, &c);
777 | break;
778 | default:
779 | second = (char *)malloc(sizeof(char) * token_size);
780 | if (token != NULL) {
781 | strncpy(second, token, token_size);
782 | }else {
783 | second = NULL;
784 | }
785 | status = TJSON_OUT_OF_TOKEN;
786 | save = is_dirty;
787 | break;
788 | }
789 | break;
790 | default:
791 | if (escape_char_status == TJSON_IN_ESCAPE_CHAR) {
792 | switch (c) {
793 | case 'b':
794 | case 'f':
795 | case 'n':
796 | case 'r':
797 | case 't':
798 | __append_char(&token, ++token_size, &c);
799 | escape_char_status = TJSON_OUT_OF_ESCAPE_CHAR;
800 | break;
801 | default:
802 | return line_number;
803 | }
804 | break;
805 | }
806 | switch (status) {
807 | case TJSON_IN_STRING_TOKEN:
808 | break;
809 | case TJSON_IN_NUMBER_TOKEN:
810 | if (!isdigit(c)
811 | && c != '.'
812 | && c != '-'
813 | && c != '+'
814 | && c != 'e'
815 | && c != 'E') return line_number;
816 | break;
817 | case TJSON_IN_BOOL_TOKEN:
818 | if (c != 't'
819 | && c != 'r'
820 | && c != 'u'
821 | && c != 'e'
822 | && c != 'f'
823 | && c != 'a'
824 | && c != 'l'
825 | && c != 's') return line_number;
826 | break;
827 | case TJSON_IN_NULL_TOKEN:
828 | if (c != 'n'
829 | && c != 'u'
830 | && c != 'l') return line_number;
831 | break;
832 | case TJSON_OUT_OF_TOKEN:
833 | token = NULL;
834 | token_size = 1;
835 | is_dirty = true;
836 | if (isdigit(c) || c == '-') {
837 | status = TJSON_IN_NUMBER_TOKEN;
838 | token_type = TJSON_NUMBER;
839 | }
840 | else if (c == 't' || c == 'f') {
841 | status = TJSON_IN_BOOL_TOKEN;
842 | token_type = TJSON_BOOL;
843 | }
844 | else if (c == 'n') {
845 | status = TJSON_IN_NULL_TOKEN;
846 | token_type = TJSON_NULL;
847 | }
848 | break;
849 | default:
850 | return line_number;
851 | }
852 | __append_char(&token, ++token_size, &c);
853 | break;
854 | }
855 |
856 | if (save) {
857 | new = NULL;
858 |
859 | //printf("(SAVE) %s:%s\n", first, second);
860 |
861 | switch (token_type){
862 | case TJSON_STRING:
863 | new = tjson_create_node_string(first, second);
864 | if (new == NULL) {
865 | return line_number;
866 | }
867 | tjson_push(¤t, new);
868 | break;
869 | case TJSON_NUMBER:
870 | v_number = strtod(second, NULL);
871 | new = tjson_create_node_number(first, v_number);
872 | if (new == NULL) {
873 | return line_number;
874 | }
875 | tjson_push(¤t, new);
876 | break;
877 | case TJSON_BOOL:
878 | if (strcmp(second, "true") == 0 || strcmp(second, "false") == 0) {
879 | v_bool = true ? strcmp(second, "true") == 0 : false;
880 | new = tjson_create_node_bool(first, v_bool);
881 | }else {
882 | return line_number;
883 | }
884 | if (new == NULL) return line_number;
885 | tjson_push(¤t, new);
886 | break;
887 | case TJSON_NULL:
888 | if (strcmp(second, "null") == 0)
889 | new = tjson_create_node_null(first);
890 | else {
891 | return line_number;
892 | }
893 | if (new == NULL) return line_number;
894 | tjson_push(¤t, new);
895 | break;
896 | case TJSON_ARRAY:
897 | new = tjson_create_node_array(first);
898 | if (new == NULL) return line_number;
899 | tjson_push(¤t, new);
900 | __stack_push(&stack, current);
901 | current = new;
902 | break;
903 | case TJSON_OBJECT:
904 | new = tjson_create_node_object(first);
905 | if (new == NULL) return line_number;
906 | tjson_push(¤t, new);
907 | __stack_push(&stack, current);
908 | current = new;
909 | break;
910 | default:
911 | return line_number;
912 | }
913 |
914 | if (first != NULL) free(first);
915 | if (second != NULL) free(second);
916 | first = second = NULL;
917 | is_dirty = save = false;
918 | }
919 |
920 | if (end_of_object_f) {
921 | if (current->v_type != TJSON_OBJECT) return line_number;
922 | current = __stack_pop(&stack);
923 | end_of_object_f = false;
924 | }
925 |
926 | if (end_of_array_f) {
927 | if (current->v_type != TJSON_ARRAY) return line_number;
928 | current = __stack_pop(&stack);
929 | end_of_array_f = false;
930 | }
931 |
932 | } while (c != '\0');
933 |
934 | if (stack != NULL) {
935 | free(stack);
936 | return line_number;
937 | }
938 |
939 | return 0;
940 | }
941 | #endif //__IGNORE_
942 |
943 | char *tjson_read_file(const char *file)
944 | {
945 | FILE *fp;
946 | long f_size;
947 | char *stream;
948 |
949 | fp = NULL;
950 | f_size = 0;
951 | stream = NULL;
952 |
953 | fp = fopen(file, "r");
954 | if (fp == NULL) return NULL;
955 |
956 | fseek(fp, 0L, SEEK_END);
957 | f_size = ftell(fp);
958 | fseek(fp, 0L, SEEK_SET);
959 |
960 | stream = (char *)malloc(sizeof(char) * (f_size + 1));
961 | fread(stream, sizeof(char), f_size, fp);
962 | fclose(fp);
963 |
964 | stream[f_size] = '\0';
965 |
966 | return stream;
967 | }
968 |
969 | void tjson_write_file(char *file, TJSON_t *json)
970 | {
971 | FILE *fp;
972 | fp = fopen(file, "w");
973 | if(fp == NULL) return;
974 |
975 | __tjson_print(json->child, fp, json->v_type, 1);
976 |
977 | fclose(fp);
978 | }
979 |
980 | #endif //__TANTO_H
981 |
--------------------------------------------------------------------------------
/tests/.gitignore:
--------------------------------------------------------------------------------
1 | result/
--------------------------------------------------------------------------------
/tests/acutest.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Acutest -- Another C/C++ Unit Test facility
3 | *
4 | *
5 | * Copyright 2013-2020 Martin Mitas
6 | * Copyright 2019 Garrett D'Amore
7 | *
8 | * Permission is hereby granted, free of charge, to any person obtaining a
9 | * copy of this software and associated documentation files (the "Software"),
10 | * to deal in the Software without restriction, including without limitation
11 | * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 | * and/or sell copies of the Software, and to permit persons to whom the
13 | * Software is furnished to do so, subject to the following conditions:
14 | *
15 | * The above copyright notice and this permission notice shall be included in
16 | * all copies or substantial portions of the Software.
17 | *
18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24 | * IN THE SOFTWARE.
25 | */
26 |
27 | #ifndef ACUTEST_H
28 | #define ACUTEST_H
29 |
30 |
31 | /************************
32 | *** Public interface ***
33 | ************************/
34 |
35 | /* By default, "acutest.h" provides the main program entry point (function
36 | * main()). However, if the test suite is composed of multiple source files
37 | * which include "acutest.h", then this causes a problem of multiple main()
38 | * definitions. To avoid this problem, #define macro TEST_NO_MAIN in all
39 | * compilation units but one.
40 | */
41 |
42 | /* Macro to specify list of unit tests in the suite.
43 | * The unit test implementation MUST provide list of unit tests it implements
44 | * with this macro:
45 | *
46 | * TEST_LIST = {
47 | * { "test1_name", test1_func_ptr },
48 | * { "test2_name", test2_func_ptr },
49 | * ...
50 | * { 0 }
51 | * };
52 | *
53 | * The list specifies names of each test (must be unique) and pointer to
54 | * a function implementing it. The function does not take any arguments
55 | * and has no return values, i.e. every test function has to be compatible
56 | * with this prototype:
57 | *
58 | * void test_func(void);
59 | */
60 | #define TEST_LIST const struct test_ test_list_[]
61 |
62 |
63 | /* Macros for testing whether an unit test succeeds or fails. These macros
64 | * can be used arbitrarily in functions implementing the unit tests.
65 | *
66 | * If any condition fails throughout execution of a test, the test fails.
67 | *
68 | * TEST_CHECK takes only one argument (the condition), TEST_CHECK_ allows
69 | * also to specify an error message to print out if the condition fails.
70 | * (It expects printf-like format string and its parameters). The macros
71 | * return non-zero (condition passes) or 0 (condition fails).
72 | *
73 | * That can be useful when more conditions should be checked only if some
74 | * preceding condition passes, as illustrated in this code snippet:
75 | *
76 | * SomeStruct* ptr = allocate_some_struct();
77 | * if(TEST_CHECK(ptr != NULL)) {
78 | * TEST_CHECK(ptr->member1 < 100);
79 | * TEST_CHECK(ptr->member2 > 200);
80 | * }
81 | */
82 | #define TEST_CHECK_(cond,...) test_check_((cond), __FILE__, __LINE__, __VA_ARGS__)
83 | #define TEST_CHECK(cond) test_check_((cond), __FILE__, __LINE__, "%s", #cond)
84 |
85 |
86 | /* These macros are the same as TEST_CHECK_ and TEST_CHECK except that if the
87 | * condition fails, the currently executed unit test is immediately aborted.
88 | *
89 | * That is done either by calling abort() if the unit test is executed as a
90 | * child process; or via longjmp() if the unit test is executed within the
91 | * main Acutest process.
92 | *
93 | * As a side effect of such abortion, your unit tests may cause memory leaks,
94 | * unflushed file descriptors, and other phenomena caused by the abortion.
95 | *
96 | * Therefore you should not use these as a general replacement for TEST_CHECK.
97 | * Use it with some caution, especially if your test causes some other side
98 | * effects to the outside world (e.g. communicating with some server, inserting
99 | * into a database etc.).
100 | */
101 | #define TEST_ASSERT_(cond,...) \
102 | do { \
103 | if(!test_check_((cond), __FILE__, __LINE__, __VA_ARGS__)) \
104 | test_abort_(); \
105 | } while(0)
106 | #define TEST_ASSERT(cond) \
107 | do { \
108 | if(!test_check_((cond), __FILE__, __LINE__, "%s", #cond)) \
109 | test_abort_(); \
110 | } while(0)
111 |
112 |
113 | #ifdef __cplusplus
114 | /* Macros to verify that the code (the 1st argument) throws exception of given
115 | * type (the 2nd argument). (Note these macros are only available in C++.)
116 | *
117 | * TEST_EXCEPTION_ is like TEST_EXCEPTION but accepts custom printf-like
118 | * message.
119 | *
120 | * For example:
121 | *
122 | * TEST_EXCEPTION(function_that_throw(), ExpectedExceptionType);
123 | *
124 | * If the function_that_throw() throws ExpectedExceptionType, the check passes.
125 | * If the function throws anything incompatible with ExpectedExceptionType
126 | * (or if it does not thrown an exception at all), the check fails.
127 | */
128 | #define TEST_EXCEPTION(code, exctype) \
129 | do { \
130 | bool exc_ok_ = false; \
131 | const char *msg_ = NULL; \
132 | try { \
133 | code; \
134 | msg_ = "No exception thrown."; \
135 | } catch(exctype const&) { \
136 | exc_ok_= true; \
137 | } catch(...) { \
138 | msg_ = "Unexpected exception thrown."; \
139 | } \
140 | test_check_(exc_ok_, __FILE__, __LINE__, #code " throws " #exctype); \
141 | if(msg_ != NULL) \
142 | test_message_("%s", msg_); \
143 | } while(0)
144 | #define TEST_EXCEPTION_(code, exctype, ...) \
145 | do { \
146 | bool exc_ok_ = false; \
147 | const char *msg_ = NULL; \
148 | try { \
149 | code; \
150 | msg_ = "No exception thrown."; \
151 | } catch(exctype const&) { \
152 | exc_ok_= true; \
153 | } catch(...) { \
154 | msg_ = "Unexpected exception thrown."; \
155 | } \
156 | test_check_(exc_ok_, __FILE__, __LINE__, __VA_ARGS__); \
157 | if(msg_ != NULL) \
158 | test_message_("%s", msg_); \
159 | } while(0)
160 | #endif /* #ifdef __cplusplus */
161 |
162 |
163 | /* Sometimes it is useful to split execution of more complex unit tests to some
164 | * smaller parts and associate those parts with some names.
165 | *
166 | * This is especially handy if the given unit test is implemented as a loop
167 | * over some vector of multiple testing inputs. Using these macros allow to use
168 | * sort of subtitle for each iteration of the loop (e.g. outputting the input
169 | * itself or a name associated to it), so that if any TEST_CHECK condition
170 | * fails in the loop, it can be easily seen which iteration triggers the
171 | * failure, without the need to manually output the iteration-specific data in
172 | * every single TEST_CHECK inside the loop body.
173 | *
174 | * TEST_CASE allows to specify only single string as the name of the case,
175 | * TEST_CASE_ provides all the power of printf-like string formatting.
176 | *
177 | * Note that the test cases cannot be nested. Starting a new test case ends
178 | * implicitly the previous one. To end the test case explicitly (e.g. to end
179 | * the last test case after exiting the loop), you may use TEST_CASE(NULL).
180 | */
181 | #define TEST_CASE_(...) test_case_(__VA_ARGS__)
182 | #define TEST_CASE(name) test_case_("%s", name)
183 |
184 |
185 | /* Maximal output per TEST_CASE call. Longer messages are cut.
186 | * You may define another limit prior including "acutest.h"
187 | */
188 | #ifndef TEST_CASE_MAXSIZE
189 | #define TEST_CASE_MAXSIZE 64
190 | #endif
191 |
192 |
193 | /* printf-like macro for outputting an extra information about a failure.
194 | *
195 | * Intended use is to output some computed output versus the expected value,
196 | * e.g. like this:
197 | *
198 | * if(!TEST_CHECK(produced == expected)) {
199 | * TEST_MSG("Expected: %d", expected);
200 | * TEST_MSG("Produced: %d", produced);
201 | * }
202 | *
203 | * Note the message is only written down if the most recent use of any checking
204 | * macro (like e.g. TEST_CHECK or TEST_EXCEPTION) in the current test failed.
205 | * This means the above is equivalent to just this:
206 | *
207 | * TEST_CHECK(produced == expected);
208 | * TEST_MSG("Expected: %d", expected);
209 | * TEST_MSG("Produced: %d", produced);
210 | *
211 | * The macro can deal with multi-line output fairly well. It also automatically
212 | * adds a final new-line if there is none present.
213 | */
214 | #define TEST_MSG(...) test_message_(__VA_ARGS__)
215 |
216 |
217 | /* Maximal output per TEST_MSG call. Longer messages are cut.
218 | * You may define another limit prior including "acutest.h"
219 | */
220 | #ifndef TEST_MSG_MAXSIZE
221 | #define TEST_MSG_MAXSIZE 1024
222 | #endif
223 |
224 |
225 | /* Macro for dumping a block of memory.
226 | *
227 | * Its intended use is very similar to what TEST_MSG is for, but instead of
228 | * generating any printf-like message, this is for dumping raw block of a
229 | * memory in a hexadecimal form:
230 | *
231 | * TEST_CHECK(size_produced == size_expected &&
232 | * memcmp(addr_produced, addr_expected, size_produced) == 0);
233 | * TEST_DUMP("Expected:", addr_expected, size_expected);
234 | * TEST_DUMP("Produced:", addr_produced, size_produced);
235 | */
236 | #define TEST_DUMP(title, addr, size) test_dump_(title, addr, size)
237 |
238 | /* Maximal output per TEST_DUMP call (in bytes to dump). Longer blocks are cut.
239 | * You may define another limit prior including "acutest.h"
240 | */
241 | #ifndef TEST_DUMP_MAXSIZE
242 | #define TEST_DUMP_MAXSIZE 1024
243 | #endif
244 |
245 |
246 | /* Common test initialiation/clean-up
247 | *
248 | * In some test suites, it may be needed to perform some sort of the same
249 | * initialization and/or clean-up in all the tests.
250 | *
251 | * Such test suites may use macros TEST_INIT and/or TEST_FINI prior including
252 | * this header. The expansion of the macro is then used as a body of helper
253 | * function called just before executing every single (TEST_INIT) or just after
254 | * it ends (TEST_FINI).
255 | *
256 | * Examples of various ways how to use the macro TEST_INIT:
257 | *
258 | * #define TEST_INIT my_init_func();
259 | * #define TEST_INIT my_init_func() // Works even without the semicolon
260 | * #define TEST_INIT setlocale(LC_ALL, NULL);
261 | * #define TEST_INIT { setlocale(LC_ALL, NULL); my_init_func(); }
262 | *
263 | * TEST_FINI is to be used in the same way.
264 | */
265 |
266 |
267 | /**********************
268 | *** Implementation ***
269 | **********************/
270 |
271 | /* The unit test files should not rely on anything below. */
272 |
273 | #include
274 | #include
275 | #include
276 | #include
277 | #include
278 | #include
279 |
280 | #if defined(unix) || defined(__unix__) || defined(__unix) || defined(__APPLE__)
281 | #define ACUTEST_UNIX_ 1
282 | #include
283 | #include
284 | #include
285 | #include
286 | #include
287 | #include
288 | #include
289 |
290 | #if defined CLOCK_PROCESS_CPUTIME_ID && defined CLOCK_MONOTONIC
291 | #define ACUTEST_HAS_POSIX_TIMER_ 1
292 | #endif
293 | #endif
294 |
295 | #if defined(_gnu_linux_)
296 | #define ACUTEST_LINUX_ 1
297 | #include
298 | #include
299 | #endif
300 |
301 | #if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__)
302 | #define ACUTEST_WIN_ 1
303 | #include
304 | #include
305 | #endif
306 |
307 | #ifdef __cplusplus
308 | #include
309 | #endif
310 |
311 | /* Load valgrind.h, if available. This allows to detect valgrind's presence via RUNNING_ON_VALGRIND. */
312 | #ifdef __has_include
313 | #if __has_include()
314 | #include
315 | #endif
316 | #endif
317 |
318 | /* Enable the use of the non-standard keyword __attribute__ to silence warnings under some compilers */
319 | #if defined(__GNUC__) || defined(__clang__)
320 | #define TEST_ATTRIBUTE_(attr) __attribute__((attr))
321 | #else
322 | #define TEST_ATTRIBUTE_(attr)
323 | #endif
324 |
325 | /* Note our global private identifiers end with '_' to mitigate risk of clash
326 | * with the unit tests implementation. */
327 |
328 | #ifdef __cplusplus
329 | extern "C" {
330 | #endif
331 |
332 | #ifdef _MSC_VER
333 | /* In the multi-platform code like ours, we cannot use the non-standard
334 | * "safe" functions from Microsoft C lib like e.g. sprintf_s() instead of
335 | * standard sprintf(). Hence, lets disable the warning C4996. */
336 | #pragma warning(push)
337 | #pragma warning(disable: 4996)
338 | #endif
339 |
340 |
341 | struct test_ {
342 | const char* name;
343 | void (*func)(void);
344 | };
345 |
346 | struct test_detail_ {
347 | unsigned char flags;
348 | double duration;
349 | };
350 |
351 | enum {
352 | TEST_FLAG_RUN_ = 1 << 0,
353 | TEST_FLAG_SUCCESS_ = 1 << 1,
354 | TEST_FLAG_FAILURE_ = 1 << 2,
355 | };
356 |
357 | extern const struct test_ test_list_[];
358 |
359 | int test_check_(int cond, const char* file, int line, const char* fmt, ...);
360 | void test_case_(const char* fmt, ...);
361 | void test_message_(const char* fmt, ...);
362 | void test_dump_(const char* title, const void* addr, size_t size);
363 | void test_abort_(void) TEST_ATTRIBUTE_(noreturn);
364 |
365 |
366 | #ifndef TEST_NO_MAIN
367 |
368 | static char* test_argv0_ = NULL;
369 | static size_t test_list_size_ = 0;
370 | static struct test_detail_ *test_details_ = NULL;
371 | static size_t test_count_ = 0;
372 | static int test_no_exec_ = -1;
373 | static int test_no_summary_ = 0;
374 | static int test_tap_ = 0;
375 | static int test_skip_mode_ = 0;
376 | static int test_worker_ = 0;
377 | static int test_worker_index_ = 0;
378 | static int test_cond_failed_ = 0;
379 | static int test_was_aborted_ = 0;
380 | static FILE *test_xml_output_ = NULL;
381 |
382 | static int test_stat_failed_units_ = 0;
383 | static int test_stat_run_units_ = 0;
384 |
385 | static const struct test_* test_current_unit_ = NULL;
386 | static int test_current_index_ = 0;
387 | static char test_case_name_[TEST_CASE_MAXSIZE] = "";
388 | static int test_current_already_logged_ = 0;
389 | static int test_case_current_already_logged_ = 0;
390 | static int test_verbose_level_ = 2;
391 | static int test_current_failures_ = 0;
392 | static int test_colorize_ = 0;
393 | static int test_timer_ = 0;
394 |
395 | static int test_abort_has_jmp_buf_ = 0;
396 | static jmp_buf test_abort_jmp_buf_;
397 |
398 | #if defined ACUTEST_WIN_
399 | typedef LARGE_INTEGER test_timer_type_;
400 | static LARGE_INTEGER test_timer_freq_;
401 | static test_timer_type_ test_timer_start_;
402 | static test_timer_type_ test_timer_end_;
403 |
404 | static void
405 | test_timer_init_(void)
406 | {
407 | QueryPerformanceFrequency(&test_timer_freq_);
408 | }
409 |
410 | static void
411 | test_timer_get_time_(LARGE_INTEGER* ts)
412 | {
413 | QueryPerformanceCounter(ts);
414 | }
415 |
416 | static double
417 | test_timer_diff_(LARGE_INTEGER start, LARGE_INTEGER end)
418 | {
419 | double duration = (double)(end.QuadPart - start.QuadPart);
420 | duration /= (double)test_timer_freq_.QuadPart;
421 | return duration;
422 | }
423 |
424 | static void
425 | test_timer_print_diff_(void)
426 | {
427 | printf("%.6lf secs", test_timer_diff_(test_timer_start_, test_timer_end_));
428 | }
429 | #elif defined ACUTEST_HAS_POSIX_TIMER_
430 | static clockid_t test_timer_id_;
431 | typedef struct timespec test_timer_type_;
432 | static test_timer_type_ test_timer_start_;
433 | static test_timer_type_ test_timer_end_;
434 |
435 | static void
436 | test_timer_init_(void)
437 | {
438 | if(test_timer_ == 1)
439 | test_timer_id_ = CLOCK_MONOTONIC;
440 | else if(test_timer_ == 2)
441 | test_timer_id_ = CLOCK_PROCESS_CPUTIME_ID;
442 | }
443 |
444 | static void
445 | test_timer_get_time_(struct timespec* ts)
446 | {
447 | clock_gettime(test_timer_id_, ts);
448 | }
449 |
450 | static double
451 | test_timer_diff_(struct timespec start, struct timespec end)
452 | {
453 | double endns;
454 | double startns;
455 |
456 | endns = end.tv_sec;
457 | endns *= 1e9;
458 | endns += end.tv_nsec;
459 |
460 | startns = start.tv_sec;
461 | startns *= 1e9;
462 | startns += start.tv_nsec;
463 |
464 | return ((endns - startns)/ 1e9);
465 | }
466 |
467 | static void
468 | test_timer_print_diff_(void)
469 | {
470 | printf("%.6lf secs",
471 | test_timer_diff_(test_timer_start_, test_timer_end_));
472 | }
473 | #else
474 | typedef int test_timer_type_;
475 | static test_timer_type_ test_timer_start_;
476 | static test_timer_type_ test_timer_end_;
477 |
478 | void
479 | test_timer_init_(void)
480 | {}
481 |
482 | static void
483 | test_timer_get_time_(int* ts)
484 | {
485 | (void) ts;
486 | }
487 |
488 | static double
489 | test_timer_diff_(int start, int end)
490 | {
491 | (void) start;
492 | (void) end;
493 | return 0.0;
494 | }
495 |
496 | static void
497 | test_timer_print_diff_(void)
498 | {}
499 | #endif
500 |
501 | #define TEST_COLOR_DEFAULT_ 0
502 | #define TEST_COLOR_GREEN_ 1
503 | #define TEST_COLOR_RED_ 2
504 | #define TEST_COLOR_DEFAULT_INTENSIVE_ 3
505 | #define TEST_COLOR_GREEN_INTENSIVE_ 4
506 | #define TEST_COLOR_RED_INTENSIVE_ 5
507 |
508 | static int TEST_ATTRIBUTE_(format (printf, 2, 3))
509 | test_print_in_color_(int color, const char* fmt, ...)
510 | {
511 | va_list args;
512 | char buffer[256];
513 | int n;
514 |
515 | va_start(args, fmt);
516 | vsnprintf(buffer, sizeof(buffer), fmt, args);
517 | va_end(args);
518 | buffer[sizeof(buffer)-1] = '\0';
519 |
520 | if(!test_colorize_) {
521 | return printf("%s", buffer);
522 | }
523 |
524 | #if defined ACUTEST_UNIX_
525 | {
526 | const char* col_str;
527 | switch(color) {
528 | case TEST_COLOR_GREEN_: col_str = "\033[0;32m"; break;
529 | case TEST_COLOR_RED_: col_str = "\033[0;31m"; break;
530 | case TEST_COLOR_GREEN_INTENSIVE_: col_str = "\033[1;32m"; break;
531 | case TEST_COLOR_RED_INTENSIVE_: col_str = "\033[1;31m"; break;
532 | case TEST_COLOR_DEFAULT_INTENSIVE_: col_str = "\033[1m"; break;
533 | default: col_str = "\033[0m"; break;
534 | }
535 | printf("%s", col_str);
536 | n = printf("%s", buffer);
537 | printf("\033[0m");
538 | return n;
539 | }
540 | #elif defined ACUTEST_WIN_
541 | {
542 | HANDLE h;
543 | CONSOLE_SCREEN_BUFFER_INFO info;
544 | WORD attr;
545 |
546 | h = GetStdHandle(STD_OUTPUT_HANDLE);
547 | GetConsoleScreenBufferInfo(h, &info);
548 |
549 | switch(color) {
550 | case TEST_COLOR_GREEN_: attr = FOREGROUND_GREEN; break;
551 | case TEST_COLOR_RED_: attr = FOREGROUND_RED; break;
552 | case TEST_COLOR_GREEN_INTENSIVE_: attr = FOREGROUND_GREEN | FOREGROUND_INTENSITY; break;
553 | case TEST_COLOR_RED_INTENSIVE_: attr = FOREGROUND_RED | FOREGROUND_INTENSITY; break;
554 | case TEST_COLOR_DEFAULT_INTENSIVE_: attr = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY; break;
555 | default: attr = 0; break;
556 | }
557 | if(attr != 0)
558 | SetConsoleTextAttribute(h, attr);
559 | n = printf("%s", buffer);
560 | SetConsoleTextAttribute(h, info.wAttributes);
561 | return n;
562 | }
563 | #else
564 | n = printf("%s", buffer);
565 | return n;
566 | #endif
567 | }
568 |
569 | static void
570 | test_begin_test_line_(const struct test_* test)
571 | {
572 | if(!test_tap_) {
573 | if(test_verbose_level_ >= 3) {
574 | test_print_in_color_(TEST_COLOR_DEFAULT_INTENSIVE_, "Test %s:\n", test->name);
575 | test_current_already_logged_++;
576 | } else if(test_verbose_level_ >= 1) {
577 | int n;
578 | char spaces[48];
579 |
580 | n = test_print_in_color_(TEST_COLOR_DEFAULT_INTENSIVE_, "Test %s... ", test->name);
581 | memset(spaces, ' ', sizeof(spaces));
582 | if(n < (int) sizeof(spaces))
583 | printf("%.*s", (int) sizeof(spaces) - n, spaces);
584 | } else {
585 | test_current_already_logged_ = 1;
586 | }
587 | }
588 | }
589 |
590 | static void
591 | test_finish_test_line_(int result)
592 | {
593 | if(test_tap_) {
594 | const char* str = (result == 0) ? "ok" : "not ok";
595 |
596 | printf("%s %d - %s\n", str, test_current_index_ + 1, test_current_unit_->name);
597 |
598 | if(result == 0 && test_timer_) {
599 | printf("# Duration: ");
600 | test_timer_print_diff_();
601 | printf("\n");
602 | }
603 | } else {
604 | int color = (result == 0) ? TEST_COLOR_GREEN_INTENSIVE_ : TEST_COLOR_RED_INTENSIVE_;
605 | const char* str = (result == 0) ? "OK" : "FAILED";
606 | printf("[ ");
607 | test_print_in_color_(color, "%s", str);
608 | printf(" ]");
609 |
610 | if(result == 0 && test_timer_) {
611 | printf(" ");
612 | test_timer_print_diff_();
613 | }
614 |
615 | printf("\n");
616 | }
617 | }
618 |
619 | static void
620 | test_line_indent_(int level)
621 | {
622 | static const char spaces[] = " ";
623 | int n = level * 2;
624 |
625 | if(test_tap_ && n > 0) {
626 | n--;
627 | printf("#");
628 | }
629 |
630 | while(n > 16) {
631 | printf("%s", spaces);
632 | n -= 16;
633 | }
634 | printf("%.*s", n, spaces);
635 | }
636 |
637 | int TEST_ATTRIBUTE_(format (printf, 4, 5))
638 | test_check_(int cond, const char* file, int line, const char* fmt, ...)
639 | {
640 | const char *result_str;
641 | int result_color;
642 | int verbose_level;
643 |
644 | if(cond) {
645 | result_str = "ok";
646 | result_color = TEST_COLOR_GREEN_;
647 | verbose_level = 3;
648 | } else {
649 | if(!test_current_already_logged_ && test_current_unit_ != NULL)
650 | test_finish_test_line_(-1);
651 |
652 | result_str = "failed";
653 | result_color = TEST_COLOR_RED_;
654 | verbose_level = 2;
655 | test_current_failures_++;
656 | test_current_already_logged_++;
657 | }
658 |
659 | if(test_verbose_level_ >= verbose_level) {
660 | va_list args;
661 |
662 | if(!test_case_current_already_logged_ && test_case_name_[0]) {
663 | test_line_indent_(1);
664 | test_print_in_color_(TEST_COLOR_DEFAULT_INTENSIVE_, "Case %s:\n", test_case_name_);
665 | test_current_already_logged_++;
666 | test_case_current_already_logged_++;
667 | }
668 |
669 | test_line_indent_(test_case_name_[0] ? 2 : 1);
670 | if(file != NULL) {
671 | #ifdef ACUTEST_WIN_
672 | const char* lastsep1 = strrchr(file, '\\');
673 | const char* lastsep2 = strrchr(file, '/');
674 | if(lastsep1 == NULL)
675 | lastsep1 = file-1;
676 | if(lastsep2 == NULL)
677 | lastsep2 = file-1;
678 | file = (lastsep1 > lastsep2 ? lastsep1 : lastsep2) + 1;
679 | #else
680 | const char* lastsep = strrchr(file, '/');
681 | if(lastsep != NULL)
682 | file = lastsep+1;
683 | #endif
684 | printf("%s:%d: Check ", file, line);
685 | }
686 |
687 | va_start(args, fmt);
688 | vprintf(fmt, args);
689 | va_end(args);
690 |
691 | printf("... ");
692 | test_print_in_color_(result_color, "%s", result_str);
693 | printf("\n");
694 | test_current_already_logged_++;
695 | }
696 |
697 | test_cond_failed_ = (cond == 0);
698 | return !test_cond_failed_;
699 | }
700 |
701 | void TEST_ATTRIBUTE_(format (printf, 1, 2))
702 | test_case_(const char* fmt, ...)
703 | {
704 | va_list args;
705 |
706 | if(test_verbose_level_ < 2)
707 | return;
708 |
709 | if(test_case_name_[0]) {
710 | test_case_current_already_logged_ = 0;
711 | test_case_name_[0] = '\0';
712 | }
713 |
714 | if(fmt == NULL)
715 | return;
716 |
717 | va_start(args, fmt);
718 | vsnprintf(test_case_name_, sizeof(test_case_name_) - 1, fmt, args);
719 | va_end(args);
720 | test_case_name_[sizeof(test_case_name_) - 1] = '\0';
721 |
722 | if(test_verbose_level_ >= 3) {
723 | test_line_indent_(1);
724 | test_print_in_color_(TEST_COLOR_DEFAULT_INTENSIVE_, "Case %s:\n", test_case_name_);
725 | test_current_already_logged_++;
726 | test_case_current_already_logged_++;
727 | }
728 | }
729 |
730 | void TEST_ATTRIBUTE_(format (printf, 1, 2))
731 | test_message_(const char* fmt, ...)
732 | {
733 | char buffer[TEST_MSG_MAXSIZE];
734 | char* line_beg;
735 | char* line_end;
736 | va_list args;
737 |
738 | if(test_verbose_level_ < 2)
739 | return;
740 |
741 | /* We allow extra message only when something is already wrong in the
742 | * current test. */
743 | if(test_current_unit_ == NULL || !test_cond_failed_)
744 | return;
745 |
746 | va_start(args, fmt);
747 | vsnprintf(buffer, TEST_MSG_MAXSIZE, fmt, args);
748 | va_end(args);
749 | buffer[TEST_MSG_MAXSIZE-1] = '\0';
750 |
751 | line_beg = buffer;
752 | while(1) {
753 | line_end = strchr(line_beg, '\n');
754 | if(line_end == NULL)
755 | break;
756 | test_line_indent_(test_case_name_[0] ? 3 : 2);
757 | printf("%.*s\n", (int)(line_end - line_beg), line_beg);
758 | line_beg = line_end + 1;
759 | }
760 | if(line_beg[0] != '\0') {
761 | test_line_indent_(test_case_name_[0] ? 3 : 2);
762 | printf("%s\n", line_beg);
763 | }
764 | }
765 |
766 | void
767 | test_dump_(const char* title, const void* addr, size_t size)
768 | {
769 | static const size_t BYTES_PER_LINE = 16;
770 | size_t line_beg;
771 | size_t truncate = 0;
772 |
773 | if(test_verbose_level_ < 2)
774 | return;
775 |
776 | /* We allow extra message only when something is already wrong in the
777 | * current test. */
778 | if(test_current_unit_ == NULL || !test_cond_failed_)
779 | return;
780 |
781 | if(size > TEST_DUMP_MAXSIZE) {
782 | truncate = size - TEST_DUMP_MAXSIZE;
783 | size = TEST_DUMP_MAXSIZE;
784 | }
785 |
786 | test_line_indent_(test_case_name_[0] ? 3 : 2);
787 | printf((title[strlen(title)-1] == ':') ? "%s\n" : "%s:\n", title);
788 |
789 | for(line_beg = 0; line_beg < size; line_beg += BYTES_PER_LINE) {
790 | size_t line_end = line_beg + BYTES_PER_LINE;
791 | size_t off;
792 |
793 | test_line_indent_(test_case_name_[0] ? 4 : 3);
794 | printf("%08lx: ", (unsigned long)line_beg);
795 | for(off = line_beg; off < line_end; off++) {
796 | if(off < size)
797 | printf(" %02x", ((const unsigned char*)addr)[off]);
798 | else
799 | printf(" ");
800 | }
801 |
802 | printf(" ");
803 | for(off = line_beg; off < line_end; off++) {
804 | unsigned char byte = ((const unsigned char*)addr)[off];
805 | if(off < size)
806 | printf("%c", (iscntrl(byte) ? '.' : byte));
807 | else
808 | break;
809 | }
810 |
811 | printf("\n");
812 | }
813 |
814 | if(truncate > 0) {
815 | test_line_indent_(test_case_name_[0] ? 4 : 3);
816 | printf(" ... (and more %u bytes)\n", (unsigned) truncate);
817 | }
818 | }
819 |
820 | void
821 | test_abort_(void)
822 | {
823 | if(test_abort_has_jmp_buf_)
824 | longjmp(test_abort_jmp_buf_, 1);
825 | else
826 | abort();
827 | }
828 |
829 | static void
830 | test_list_names_(void)
831 | {
832 | const struct test_* test;
833 |
834 | printf("Unit tests:\n");
835 | for(test = &test_list_[0]; test->func != NULL; test++)
836 | printf(" %s\n", test->name);
837 | }
838 |
839 | static void
840 | test_remember_(int i)
841 | {
842 | if(test_details_[i].flags & TEST_FLAG_RUN_)
843 | return;
844 |
845 | test_details_[i].flags |= TEST_FLAG_RUN_;
846 | test_count_++;
847 | }
848 |
849 | static void
850 | test_set_success_(int i, int success)
851 | {
852 | test_details_[i].flags |= success ? TEST_FLAG_SUCCESS_ : TEST_FLAG_FAILURE_;
853 | }
854 |
855 | static void
856 | test_set_duration_(int i, double duration)
857 | {
858 | test_details_[i].duration = duration;
859 | }
860 |
861 | static int
862 | test_name_contains_word_(const char* name, const char* pattern)
863 | {
864 | static const char word_delim[] = " \t-_/.,:;";
865 | const char* substr;
866 | size_t pattern_len;
867 |
868 | pattern_len = strlen(pattern);
869 |
870 | substr = strstr(name, pattern);
871 | while(substr != NULL) {
872 | int starts_on_word_boundary = (substr == name || strchr(word_delim, substr[-1]) != NULL);
873 | int ends_on_word_boundary = (substr[pattern_len] == '\0' || strchr(word_delim, substr[pattern_len]) != NULL);
874 |
875 | if(starts_on_word_boundary && ends_on_word_boundary)
876 | return 1;
877 |
878 | substr = strstr(substr+1, pattern);
879 | }
880 |
881 | return 0;
882 | }
883 |
884 | static int
885 | test_lookup_(const char* pattern)
886 | {
887 | int i;
888 | int n = 0;
889 |
890 | /* Try exact match. */
891 | for(i = 0; i < (int) test_list_size_; i++) {
892 | if(strcmp(test_list_[i].name, pattern) == 0) {
893 | test_remember_(i);
894 | n++;
895 | break;
896 | }
897 | }
898 | if(n > 0)
899 | return n;
900 |
901 | /* Try word match. */
902 | for(i = 0; i < (int) test_list_size_; i++) {
903 | if(test_name_contains_word_(test_list_[i].name, pattern)) {
904 | test_remember_(i);
905 | n++;
906 | }
907 | }
908 | if(n > 0)
909 | return n;
910 |
911 | /* Try relaxed match. */
912 | for(i = 0; i < (int) test_list_size_; i++) {
913 | if(strstr(test_list_[i].name, pattern) != NULL) {
914 | test_remember_(i);
915 | n++;
916 | }
917 | }
918 |
919 | return n;
920 | }
921 |
922 |
923 | /* Called if anything goes bad in Acutest, or if the unit test ends in other
924 | * way then by normal returning from its function (e.g. exception or some
925 | * abnormal child process termination). */
926 | static void TEST_ATTRIBUTE_(format (printf, 1, 2))
927 | test_error_(const char* fmt, ...)
928 | {
929 | if(test_verbose_level_ == 0)
930 | return;
931 |
932 | if(test_verbose_level_ >= 2) {
933 | va_list args;
934 |
935 | test_line_indent_(1);
936 | if(test_verbose_level_ >= 3)
937 | test_print_in_color_(TEST_COLOR_RED_INTENSIVE_, "ERROR: ");
938 | va_start(args, fmt);
939 | vprintf(fmt, args);
940 | va_end(args);
941 | printf("\n");
942 | }
943 |
944 | if(test_verbose_level_ >= 3) {
945 | printf("\n");
946 | }
947 | }
948 |
949 | /* This is called just before each test */
950 | static void
951 | test_init_(const char *test_name)
952 | {
953 | #ifdef TEST_INIT
954 | TEST_INIT
955 | ; /* Allow for a single unterminated function call */
956 | #endif
957 |
958 | /* Suppress any warnings about unused variable. */
959 | (void) test_name;
960 | }
961 |
962 | /* This is called after each test */
963 | static void
964 | test_fini_(const char *test_name)
965 | {
966 | #ifdef TEST_FINI
967 | TEST_FINI
968 | ; /* Allow for a single unterminated function call */
969 | #endif
970 |
971 | /* Suppress any warnings about unused variable. */
972 | (void) test_name;
973 | }
974 |
975 | /* Call directly the given test unit function. */
976 | static int
977 | test_do_run_(const struct test_* test, int index)
978 | {
979 | int status = -1;
980 |
981 | test_was_aborted_ = 0;
982 | test_current_unit_ = test;
983 | test_current_index_ = index;
984 | test_current_failures_ = 0;
985 | test_current_already_logged_ = 0;
986 | test_cond_failed_ = 0;
987 |
988 | #ifdef __cplusplus
989 | try {
990 | #endif
991 | test_init_(test->name);
992 | test_begin_test_line_(test);
993 |
994 | /* This is good to do in case the test unit crashes. */
995 | fflush(stdout);
996 | fflush(stderr);
997 |
998 | if(!test_worker_) {
999 | test_abort_has_jmp_buf_ = 1;
1000 | if(setjmp(test_abort_jmp_buf_) != 0) {
1001 | test_was_aborted_ = 1;
1002 | goto aborted;
1003 | }
1004 | }
1005 |
1006 | test_timer_get_time_(&test_timer_start_);
1007 | test->func();
1008 | aborted:
1009 | test_abort_has_jmp_buf_ = 0;
1010 | test_timer_get_time_(&test_timer_end_);
1011 |
1012 | if(test_verbose_level_ >= 3) {
1013 | test_line_indent_(1);
1014 | if(test_current_failures_ == 0) {
1015 | test_print_in_color_(TEST_COLOR_GREEN_INTENSIVE_, "SUCCESS: ");
1016 | printf("All conditions have passed.\n");
1017 |
1018 | if(test_timer_) {
1019 | test_line_indent_(1);
1020 | printf("Duration: ");
1021 | test_timer_print_diff_();
1022 | printf("\n");
1023 | }
1024 | } else {
1025 | test_print_in_color_(TEST_COLOR_RED_INTENSIVE_, "FAILED: ");
1026 | if(!test_was_aborted_) {
1027 | printf("%d condition%s %s failed.\n",
1028 | test_current_failures_,
1029 | (test_current_failures_ == 1) ? "" : "s",
1030 | (test_current_failures_ == 1) ? "has" : "have");
1031 | } else {
1032 | printf("Aborted.\n");
1033 | }
1034 | }
1035 | printf("\n");
1036 | } else if(test_verbose_level_ >= 1 && test_current_failures_ == 0) {
1037 | test_finish_test_line_(0);
1038 | }
1039 |
1040 | status = (test_current_failures_ == 0) ? 0 : -1;
1041 |
1042 | #ifdef __cplusplus
1043 | } catch(std::exception& e) {
1044 | const char* what = e.what();
1045 | test_check_(0, NULL, 0, "Threw std::exception");
1046 | if(what != NULL)
1047 | test_message_("std::exception::what(): %s", what);
1048 |
1049 | if(test_verbose_level_ >= 3) {
1050 | test_line_indent_(1);
1051 | test_print_in_color_(TEST_COLOR_RED_INTENSIVE_, "FAILED: ");
1052 | printf("C++ exception.\n\n");
1053 | }
1054 | } catch(...) {
1055 | test_check_(0, NULL, 0, "Threw an exception");
1056 |
1057 | if(test_verbose_level_ >= 3) {
1058 | test_line_indent_(1);
1059 | test_print_in_color_(TEST_COLOR_RED_INTENSIVE_, "FAILED: ");
1060 | printf("C++ exception.\n\n");
1061 | }
1062 | }
1063 | #endif
1064 |
1065 | test_fini_(test->name);
1066 | test_case_(NULL);
1067 | test_current_unit_ = NULL;
1068 |
1069 | return status;
1070 | }
1071 |
1072 | /* Trigger the unit test. If possible (and not suppressed) it starts a child
1073 | * process who calls test_do_run_(), otherwise it calls test_do_run_()
1074 | * directly. */
1075 | static void
1076 | test_run_(const struct test_* test, int index, int master_index)
1077 | {
1078 | int failed = 1;
1079 | test_timer_type_ start, end;
1080 |
1081 | test_current_unit_ = test;
1082 | test_current_already_logged_ = 0;
1083 | test_timer_get_time_(&start);
1084 |
1085 | if(!test_no_exec_) {
1086 |
1087 | #if defined(ACUTEST_UNIX_)
1088 |
1089 | pid_t pid;
1090 | int exit_code;
1091 |
1092 | /* Make sure the child starts with empty I/O buffers. */
1093 | fflush(stdout);
1094 | fflush(stderr);
1095 |
1096 | pid = fork();
1097 | if(pid == (pid_t)-1) {
1098 | test_error_("Cannot fork. %s [%d]", strerror(errno), errno);
1099 | failed = 1;
1100 | } else if(pid == 0) {
1101 | /* Child: Do the test. */
1102 | test_worker_ = 1;
1103 | failed = (test_do_run_(test, index) != 0);
1104 | exit(failed ? 1 : 0);
1105 | } else {
1106 | /* Parent: Wait until child terminates and analyze its exit code. */
1107 | waitpid(pid, &exit_code, 0);
1108 | if(WIFEXITED(exit_code)) {
1109 | switch(WEXITSTATUS(exit_code)) {
1110 | case 0: failed = 0; break; /* test has passed. */
1111 | case 1: /* noop */ break; /* "normal" failure. */
1112 | default: test_error_("Unexpected exit code [%d]", WEXITSTATUS(exit_code));
1113 | }
1114 | } else if(WIFSIGNALED(exit_code)) {
1115 | char tmp[32];
1116 | const char* signame;
1117 | switch(WTERMSIG(exit_code)) {
1118 | case SIGINT: signame = "SIGINT"; break;
1119 | case SIGHUP: signame = "SIGHUP"; break;
1120 | case SIGQUIT: signame = "SIGQUIT"; break;
1121 | case SIGABRT: signame = "SIGABRT"; break;
1122 | case SIGKILL: signame = "SIGKILL"; break;
1123 | case SIGSEGV: signame = "SIGSEGV"; break;
1124 | case SIGILL: signame = "SIGILL"; break;
1125 | case SIGTERM: signame = "SIGTERM"; break;
1126 | default: sprintf(tmp, "signal %d", WTERMSIG(exit_code)); signame = tmp; break;
1127 | }
1128 | test_error_("Test interrupted by %s.", signame);
1129 | } else {
1130 | test_error_("Test ended in an unexpected way [%d].", exit_code);
1131 | }
1132 | }
1133 |
1134 | #elif defined(ACUTEST_WIN_)
1135 |
1136 | char buffer[512] = {0};
1137 | STARTUPINFOA startupInfo;
1138 | PROCESS_INFORMATION processInfo;
1139 | DWORD exitCode;
1140 |
1141 | /* Windows has no fork(). So we propagate all info into the child
1142 | * through a command line arguments. */
1143 | _snprintf(buffer, sizeof(buffer)-1,
1144 | "%s --worker=%d %s --no-exec --no-summary %s --verbose=%d --color=%s -- \"%s\"",
1145 | test_argv0_, index, test_timer_ ? "--time" : "",
1146 | test_tap_ ? "--tap" : "", test_verbose_level_,
1147 | test_colorize_ ? "always" : "never",
1148 | test->name);
1149 | memset(&startupInfo, 0, sizeof(startupInfo));
1150 | startupInfo.cb = sizeof(STARTUPINFO);
1151 | if(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo)) {
1152 | WaitForSingleObject(processInfo.hProcess, INFINITE);
1153 | GetExitCodeProcess(processInfo.hProcess, &exitCode);
1154 | CloseHandle(processInfo.hThread);
1155 | CloseHandle(processInfo.hProcess);
1156 | failed = (exitCode != 0);
1157 | if(exitCode > 1) {
1158 | switch(exitCode) {
1159 | case 3: test_error_("Aborted."); break;
1160 | case 0xC0000005: test_error_("Access violation."); break;
1161 | default: test_error_("Test ended in an unexpected way [%lu].", exitCode); break;
1162 | }
1163 | }
1164 | } else {
1165 | test_error_("Cannot create unit test subprocess [%ld].", GetLastError());
1166 | failed = 1;
1167 | }
1168 |
1169 | #else
1170 |
1171 | /* A platform where we don't know how to run child process. */
1172 | failed = (test_do_run_(test, index) != 0);
1173 |
1174 | #endif
1175 |
1176 | } else {
1177 | /* Child processes suppressed through --no-exec. */
1178 | failed = (test_do_run_(test, index) != 0);
1179 | }
1180 | test_timer_get_time_(&end);
1181 |
1182 | test_current_unit_ = NULL;
1183 |
1184 | test_stat_run_units_++;
1185 | if(failed)
1186 | test_stat_failed_units_++;
1187 |
1188 | test_set_success_(master_index, !failed);
1189 | test_set_duration_(master_index, test_timer_diff_(start, end));
1190 | }
1191 |
1192 | #if defined(ACUTEST_WIN_)
1193 | /* Callback for SEH events. */
1194 | static LONG CALLBACK
1195 | test_seh_exception_filter_(EXCEPTION_POINTERS *ptrs)
1196 | {
1197 | test_check_(0, NULL, 0, "Unhandled SEH exception");
1198 | test_message_("Exception code: 0x%08lx", ptrs->ExceptionRecord->ExceptionCode);
1199 | test_message_("Exception address: 0x%p", ptrs->ExceptionRecord->ExceptionAddress);
1200 |
1201 | fflush(stdout);
1202 | fflush(stderr);
1203 |
1204 | return EXCEPTION_EXECUTE_HANDLER;
1205 | }
1206 | #endif
1207 |
1208 |
1209 | #define TEST_CMDLINE_OPTFLAG_OPTIONALARG_ 0x0001
1210 | #define TEST_CMDLINE_OPTFLAG_REQUIREDARG_ 0x0002
1211 |
1212 | #define TEST_CMDLINE_OPTID_NONE_ 0
1213 | #define TEST_CMDLINE_OPTID_UNKNOWN_ (-0x7fffffff + 0)
1214 | #define TEST_CMDLINE_OPTID_MISSINGARG_ (-0x7fffffff + 1)
1215 | #define TEST_CMDLINE_OPTID_BOGUSARG_ (-0x7fffffff + 2)
1216 |
1217 | typedef struct TEST_CMDLINE_OPTION_ {
1218 | char shortname;
1219 | const char* longname;
1220 | int id;
1221 | unsigned flags;
1222 | } TEST_CMDLINE_OPTION_;
1223 |
1224 | static int
1225 | test_cmdline_handle_short_opt_group_(const TEST_CMDLINE_OPTION_* options,
1226 | const char* arggroup,
1227 | int (*callback)(int /*optval*/, const char* /*arg*/))
1228 | {
1229 | const TEST_CMDLINE_OPTION_* opt;
1230 | int i;
1231 | int ret = 0;
1232 |
1233 | for(i = 0; arggroup[i] != '\0'; i++) {
1234 | for(opt = options; opt->id != 0; opt++) {
1235 | if(arggroup[i] == opt->shortname)
1236 | break;
1237 | }
1238 |
1239 | if(opt->id != 0 && !(opt->flags & TEST_CMDLINE_OPTFLAG_REQUIREDARG_)) {
1240 | ret = callback(opt->id, NULL);
1241 | } else {
1242 | /* Unknown option. */
1243 | char badoptname[3];
1244 | badoptname[0] = '-';
1245 | badoptname[1] = arggroup[i];
1246 | badoptname[2] = '\0';
1247 | ret = callback((opt->id != 0 ? TEST_CMDLINE_OPTID_MISSINGARG_ : TEST_CMDLINE_OPTID_UNKNOWN_),
1248 | badoptname);
1249 | }
1250 |
1251 | if(ret != 0)
1252 | break;
1253 | }
1254 |
1255 | return ret;
1256 | }
1257 |
1258 | #define TEST_CMDLINE_AUXBUF_SIZE_ 32
1259 |
1260 | static int
1261 | test_cmdline_read_(const TEST_CMDLINE_OPTION_* options, int argc, char** argv,
1262 | int (*callback)(int /*optval*/, const char* /*arg*/))
1263 | {
1264 |
1265 | const TEST_CMDLINE_OPTION_* opt;
1266 | char auxbuf[TEST_CMDLINE_AUXBUF_SIZE_+1];
1267 | int after_doubledash = 0;
1268 | int i = 1;
1269 | int ret = 0;
1270 |
1271 | auxbuf[TEST_CMDLINE_AUXBUF_SIZE_] = '\0';
1272 |
1273 | while(i < argc) {
1274 | if(after_doubledash || strcmp(argv[i], "-") == 0) {
1275 | /* Non-option argument. */
1276 | ret = callback(TEST_CMDLINE_OPTID_NONE_, argv[i]);
1277 | } else if(strcmp(argv[i], "--") == 0) {
1278 | /* End of options. All the remaining members are non-option arguments. */
1279 | after_doubledash = 1;
1280 | } else if(argv[i][0] != '-') {
1281 | /* Non-option argument. */
1282 | ret = callback(TEST_CMDLINE_OPTID_NONE_, argv[i]);
1283 | } else {
1284 | for(opt = options; opt->id != 0; opt++) {
1285 | if(opt->longname != NULL && strncmp(argv[i], "--", 2) == 0) {
1286 | size_t len = strlen(opt->longname);
1287 | if(strncmp(argv[i]+2, opt->longname, len) == 0) {
1288 | /* Regular long option. */
1289 | if(argv[i][2+len] == '\0') {
1290 | /* with no argument provided. */
1291 | if(!(opt->flags & TEST_CMDLINE_OPTFLAG_REQUIREDARG_))
1292 | ret = callback(opt->id, NULL);
1293 | else
1294 | ret = callback(TEST_CMDLINE_OPTID_MISSINGARG_, argv[i]);
1295 | break;
1296 | } else if(argv[i][2+len] == '=') {
1297 | /* with an argument provided. */
1298 | if(opt->flags & (TEST_CMDLINE_OPTFLAG_OPTIONALARG_ | TEST_CMDLINE_OPTFLAG_REQUIREDARG_)) {
1299 | ret = callback(opt->id, argv[i]+2+len+1);
1300 | } else {
1301 | sprintf(auxbuf, "--%s", opt->longname);
1302 | ret = callback(TEST_CMDLINE_OPTID_BOGUSARG_, auxbuf);
1303 | }
1304 | break;
1305 | } else {
1306 | continue;
1307 | }
1308 | }
1309 | } else if(opt->shortname != '\0' && argv[i][0] == '-') {
1310 | if(argv[i][1] == opt->shortname) {
1311 | /* Regular short option. */
1312 | if(opt->flags & TEST_CMDLINE_OPTFLAG_REQUIREDARG_) {
1313 | if(argv[i][2] != '\0')
1314 | ret = callback(opt->id, argv[i]+2);
1315 | else if(i+1 < argc)
1316 | ret = callback(opt->id, argv[++i]);
1317 | else
1318 | ret = callback(TEST_CMDLINE_OPTID_MISSINGARG_, argv[i]);
1319 | break;
1320 | } else {
1321 | ret = callback(opt->id, NULL);
1322 |
1323 | /* There might be more (argument-less) short options
1324 | * grouped together. */
1325 | if(ret == 0 && argv[i][2] != '\0')
1326 | ret = test_cmdline_handle_short_opt_group_(options, argv[i]+2, callback);
1327 | break;
1328 | }
1329 | }
1330 | }
1331 | }
1332 |
1333 | if(opt->id == 0) { /* still not handled? */
1334 | if(argv[i][0] != '-') {
1335 | /* Non-option argument. */
1336 | ret = callback(TEST_CMDLINE_OPTID_NONE_, argv[i]);
1337 | } else {
1338 | /* Unknown option. */
1339 | char* badoptname = argv[i];
1340 |
1341 | if(strncmp(badoptname, "--", 2) == 0) {
1342 | /* Strip any argument from the long option. */
1343 | char* assignment = strchr(badoptname, '=');
1344 | if(assignment != NULL) {
1345 | size_t len = assignment - badoptname;
1346 | if(len > TEST_CMDLINE_AUXBUF_SIZE_)
1347 | len = TEST_CMDLINE_AUXBUF_SIZE_;
1348 | strncpy(auxbuf, badoptname, len);
1349 | auxbuf[len] = '\0';
1350 | badoptname = auxbuf;
1351 | }
1352 | }
1353 |
1354 | ret = callback(TEST_CMDLINE_OPTID_UNKNOWN_, badoptname);
1355 | }
1356 | }
1357 | }
1358 |
1359 | if(ret != 0)
1360 | return ret;
1361 | i++;
1362 | }
1363 |
1364 | return ret;
1365 | }
1366 |
1367 | static void
1368 | test_help_(void)
1369 | {
1370 | printf("Usage: %s [options] [test...]\n", test_argv0_);
1371 | printf("\n");
1372 | printf("Run the specified unit tests; or if the option '--skip' is used, run all\n");
1373 | printf("tests in the suite but those listed. By default, if no tests are specified\n");
1374 | printf("on the command line, all unit tests in the suite are run.\n");
1375 | printf("\n");
1376 | printf("Options:\n");
1377 | printf(" -s, --skip Execute all unit tests but the listed ones\n");
1378 | printf(" --exec[=WHEN] If supported, execute unit tests as child processes\n");
1379 | printf(" (WHEN is one of 'auto', 'always', 'never')\n");
1380 | printf(" -E, --no-exec Same as --exec=never\n");
1381 | #if defined ACUTEST_WIN_
1382 | printf(" -t, --time Measure test duration\n");
1383 | #elif defined ACUTEST_HAS_POSIX_TIMER_
1384 | printf(" -t, --time Measure test duration (real time)\n");
1385 | printf(" --time=TIMER Measure test duration, using given timer\n");
1386 | printf(" (TIMER is one of 'real', 'cpu')\n");
1387 | #endif
1388 | printf(" --no-summary Suppress printing of test results summary\n");
1389 | printf(" --tap Produce TAP-compliant output\n");
1390 | printf(" (See https://testanything.org/)\n");
1391 | printf(" -x, --xml-output=FILE Enable XUnit output to the given file\n");
1392 | printf(" -l, --list List unit tests in the suite and exit\n");
1393 | printf(" -v, --verbose Make output more verbose\n");
1394 | printf(" --verbose=LEVEL Set verbose level to LEVEL:\n");
1395 | printf(" 0 ... Be silent\n");
1396 | printf(" 1 ... Output one line per test (and summary)\n");
1397 | printf(" 2 ... As 1 and failed conditions (this is default)\n");
1398 | printf(" 3 ... As 1 and all conditions (and extended summary)\n");
1399 | printf(" -q, --quiet Same as --verbose=0\n");
1400 | printf(" --color[=WHEN] Enable colorized output\n");
1401 | printf(" (WHEN is one of 'auto', 'always', 'never')\n");
1402 | printf(" --no-color Same as --color=never\n");
1403 | printf(" -h, --help Display this help and exit\n");
1404 |
1405 | if(test_list_size_ < 16) {
1406 | printf("\n");
1407 | test_list_names_();
1408 | }
1409 | }
1410 |
1411 | static const TEST_CMDLINE_OPTION_ test_cmdline_options_[] = {
1412 | { 's', "skip", 's', 0 },
1413 | { 0, "exec", 'e', TEST_CMDLINE_OPTFLAG_OPTIONALARG_ },
1414 | { 'E', "no-exec", 'E', 0 },
1415 | #if defined ACUTEST_WIN_
1416 | { 't', "time", 't', 0 },
1417 | { 0, "timer", 't', 0 }, /* kept for compatibility */
1418 | #elif defined ACUTEST_HAS_POSIX_TIMER_
1419 | { 't', "time", 't', TEST_CMDLINE_OPTFLAG_OPTIONALARG_ },
1420 | { 0, "timer", 't', TEST_CMDLINE_OPTFLAG_OPTIONALARG_ }, /* kept for compatibility */
1421 | #endif
1422 | { 0, "no-summary", 'S', 0 },
1423 | { 0, "tap", 'T', 0 },
1424 | { 'l', "list", 'l', 0 },
1425 | { 'v', "verbose", 'v', TEST_CMDLINE_OPTFLAG_OPTIONALARG_ },
1426 | { 'q', "quiet", 'q', 0 },
1427 | { 0, "color", 'c', TEST_CMDLINE_OPTFLAG_OPTIONALARG_ },
1428 | { 0, "no-color", 'C', 0 },
1429 | { 'h', "help", 'h', 0 },
1430 | { 0, "worker", 'w', TEST_CMDLINE_OPTFLAG_REQUIREDARG_ }, /* internal */
1431 | { 'x', "xml-output", 'x', TEST_CMDLINE_OPTFLAG_REQUIREDARG_ },
1432 | { 0, NULL, 0, 0 }
1433 | };
1434 |
1435 | static int
1436 | test_cmdline_callback_(int id, const char* arg)
1437 | {
1438 | switch(id) {
1439 | case 's':
1440 | test_skip_mode_ = 1;
1441 | break;
1442 |
1443 | case 'e':
1444 | if(arg == NULL || strcmp(arg, "always") == 0) {
1445 | test_no_exec_ = 0;
1446 | } else if(strcmp(arg, "never") == 0) {
1447 | test_no_exec_ = 1;
1448 | } else if(strcmp(arg, "auto") == 0) {
1449 | /*noop*/
1450 | } else {
1451 | fprintf(stderr, "%s: Unrecognized argument '%s' for option --exec.\n", test_argv0_, arg);
1452 | fprintf(stderr, "Try '%s --help' for more information.\n", test_argv0_);
1453 | exit(2);
1454 | }
1455 | break;
1456 |
1457 | case 'E':
1458 | test_no_exec_ = 1;
1459 | break;
1460 |
1461 | case 't':
1462 | #if defined ACUTEST_WIN_ || defined ACUTEST_HAS_POSIX_TIMER_
1463 | if(arg == NULL || strcmp(arg, "real") == 0) {
1464 | test_timer_ = 1;
1465 | #ifndef ACUTEST_WIN_
1466 | } else if(strcmp(arg, "cpu") == 0) {
1467 | test_timer_ = 2;
1468 | #endif
1469 | } else {
1470 | fprintf(stderr, "%s: Unrecognized argument '%s' for option --time.\n", test_argv0_, arg);
1471 | fprintf(stderr, "Try '%s --help' for more information.\n", test_argv0_);
1472 | exit(2);
1473 | }
1474 | #endif
1475 | break;
1476 |
1477 | case 'S':
1478 | test_no_summary_ = 1;
1479 | break;
1480 |
1481 | case 'T':
1482 | test_tap_ = 1;
1483 | break;
1484 |
1485 | case 'l':
1486 | test_list_names_();
1487 | exit(0);
1488 |
1489 | case 'v':
1490 | test_verbose_level_ = (arg != NULL ? atoi(arg) : test_verbose_level_+1);
1491 | break;
1492 |
1493 | case 'q':
1494 | test_verbose_level_ = 0;
1495 | break;
1496 |
1497 | case 'c':
1498 | if(arg == NULL || strcmp(arg, "always") == 0) {
1499 | test_colorize_ = 1;
1500 | } else if(strcmp(arg, "never") == 0) {
1501 | test_colorize_ = 0;
1502 | } else if(strcmp(arg, "auto") == 0) {
1503 | /*noop*/
1504 | } else {
1505 | fprintf(stderr, "%s: Unrecognized argument '%s' for option --color.\n", test_argv0_, arg);
1506 | fprintf(stderr, "Try '%s --help' for more information.\n", test_argv0_);
1507 | exit(2);
1508 | }
1509 | break;
1510 |
1511 | case 'C':
1512 | test_colorize_ = 0;
1513 | break;
1514 |
1515 | case 'h':
1516 | test_help_();
1517 | exit(0);
1518 |
1519 | case 'w':
1520 | test_worker_ = 1;
1521 | test_worker_index_ = atoi(arg);
1522 | break;
1523 | case 'x':
1524 | test_xml_output_ = fopen(arg, "w");
1525 | if (!test_xml_output_) {
1526 | fprintf(stderr, "Unable to open '%s': %s\n", arg, strerror(errno));
1527 | exit(2);
1528 | }
1529 | break;
1530 |
1531 | case 0:
1532 | if(test_lookup_(arg) == 0) {
1533 | fprintf(stderr, "%s: Unrecognized unit test '%s'\n", test_argv0_, arg);
1534 | fprintf(stderr, "Try '%s --list' for list of unit tests.\n", test_argv0_);
1535 | exit(2);
1536 | }
1537 | break;
1538 |
1539 | case TEST_CMDLINE_OPTID_UNKNOWN_:
1540 | fprintf(stderr, "Unrecognized command line option '%s'.\n", arg);
1541 | fprintf(stderr, "Try '%s --help' for more information.\n", test_argv0_);
1542 | exit(2);
1543 |
1544 | case TEST_CMDLINE_OPTID_MISSINGARG_:
1545 | fprintf(stderr, "The command line option '%s' requires an argument.\n", arg);
1546 | fprintf(stderr, "Try '%s --help' for more information.\n", test_argv0_);
1547 | exit(2);
1548 |
1549 | case TEST_CMDLINE_OPTID_BOGUSARG_:
1550 | fprintf(stderr, "The command line option '%s' does not expect an argument.\n", arg);
1551 | fprintf(stderr, "Try '%s --help' for more information.\n", test_argv0_);
1552 | exit(2);
1553 | }
1554 |
1555 | return 0;
1556 | }
1557 |
1558 |
1559 | #ifdef ACUTEST_LINUX_
1560 | static int
1561 | test_is_tracer_present_(void)
1562 | {
1563 | /* Must be large enough so the line 'TracerPid: ${PID}' can fit in. */
1564 | static const int OVERLAP = 32;
1565 |
1566 | char buf[256+OVERLAP+1];
1567 | int tracer_present = 0;
1568 | int fd;
1569 | size_t n_read = 0;
1570 |
1571 | fd = open("/proc/self/status", O_RDONLY);
1572 | if(fd == -1)
1573 | return 0;
1574 |
1575 | while(1) {
1576 | static const char pattern[] = "TracerPid:";
1577 | const char* field;
1578 |
1579 | while(n_read < sizeof(buf) - 1) {
1580 | ssize_t n;
1581 |
1582 | n = read(fd, buf + n_read, sizeof(buf) - 1 - n_read);
1583 | if(n <= 0)
1584 | break;
1585 | n_read += n;
1586 | }
1587 | buf[n_read] = '\0';
1588 |
1589 | field = strstr(buf, pattern);
1590 | if(field != NULL && field < buf + sizeof(buf) - OVERLAP) {
1591 | pid_t tracer_pid = (pid_t) atoi(field + sizeof(pattern) - 1);
1592 | tracer_present = (tracer_pid != 0);
1593 | break;
1594 | }
1595 |
1596 | if(n_read == sizeof(buf)-1) {
1597 | memmove(buf, buf + sizeof(buf)-1 - OVERLAP, OVERLAP);
1598 | n_read = OVERLAP;
1599 | } else {
1600 | break;
1601 | }
1602 | }
1603 |
1604 | close(fd);
1605 | return tracer_present;
1606 | }
1607 | #endif
1608 |
1609 | int
1610 | main(int argc, char** argv)
1611 | {
1612 | int i;
1613 | test_argv0_ = argv[0];
1614 |
1615 | #if defined ACUTEST_UNIX_
1616 | test_colorize_ = isatty(STDOUT_FILENO);
1617 | #elif defined ACUTEST_WIN_
1618 | #if defined _BORLANDC_
1619 | test_colorize_ = isatty(_fileno(stdout));
1620 | #else
1621 | test_colorize_ = _isatty(_fileno(stdout));
1622 | #endif
1623 | #else
1624 | test_colorize_ = 0;
1625 | #endif
1626 |
1627 | /* Count all test units */
1628 | test_list_size_ = 0;
1629 | for(i = 0; test_list_[i].func != NULL; i++)
1630 | test_list_size_++;
1631 |
1632 | test_details_ = (struct test_detail_*)calloc(test_list_size_, sizeof(struct test_detail_));
1633 | if(test_details_ == NULL) {
1634 | fprintf(stderr, "Out of memory.\n");
1635 | exit(2);
1636 | }
1637 |
1638 | /* Parse options */
1639 | test_cmdline_read_(test_cmdline_options_, argc, argv, test_cmdline_callback_);
1640 |
1641 | /* Initialize the proper timer. */
1642 | test_timer_init_();
1643 |
1644 | #if defined(ACUTEST_WIN_)
1645 | SetUnhandledExceptionFilter(test_seh_exception_filter_);
1646 | #ifdef _MSC_VER
1647 | _set_abort_behavior(0, _WRITE_ABORT_MSG);
1648 | #endif
1649 | #endif
1650 |
1651 | /* By default, we want to run all tests. */
1652 | if(test_count_ == 0) {
1653 | for(i = 0; test_list_[i].func != NULL; i++)
1654 | test_remember_(i);
1655 | }
1656 |
1657 | /* Guess whether we want to run unit tests as child processes. */
1658 | if(test_no_exec_ < 0) {
1659 | test_no_exec_ = 0;
1660 |
1661 | if(test_count_ <= 1) {
1662 | test_no_exec_ = 1;
1663 | } else {
1664 | #ifdef ACUTEST_WIN_
1665 | if(IsDebuggerPresent())
1666 | test_no_exec_ = 1;
1667 | #endif
1668 | #ifdef ACUTEST_LINUX_
1669 | if(test_is_tracer_present_())
1670 | test_no_exec_ = 1;
1671 | #endif
1672 | #ifdef RUNNING_ON_VALGRIND
1673 | /* RUNNING_ON_VALGRIND is provided by valgrind.h */
1674 | if(RUNNING_ON_VALGRIND)
1675 | test_no_exec_ = 1;
1676 | #endif
1677 | }
1678 | }
1679 |
1680 | if(test_tap_) {
1681 | /* TAP requires we know test result ("ok", "not ok") before we output
1682 | * anything about the test, and this gets problematic for larger verbose
1683 | * levels. */
1684 | if(test_verbose_level_ > 2)
1685 | test_verbose_level_ = 2;
1686 |
1687 | /* TAP harness should provide some summary. */
1688 | test_no_summary_ = 1;
1689 |
1690 | if(!test_worker_)
1691 | printf("1..%d\n", (int) test_count_);
1692 | }
1693 |
1694 | int index = test_worker_index_;
1695 | for(i = 0; test_list_[i].func != NULL; i++) {
1696 | int run = (test_details_[i].flags & TEST_FLAG_RUN_);
1697 | if (test_skip_mode_) /* Run all tests except those listed. */
1698 | run = !run;
1699 | if(run)
1700 | test_run_(&test_list_[i], index++, i);
1701 | }
1702 |
1703 | /* Write a summary */
1704 | if(!test_no_summary_ && test_verbose_level_ >= 1) {
1705 | if(test_verbose_level_ >= 3) {
1706 | test_print_in_color_(TEST_COLOR_DEFAULT_INTENSIVE_, "Summary:\n");
1707 |
1708 | printf(" Count of all unit tests: %4d\n", (int) test_list_size_);
1709 | printf(" Count of run unit tests: %4d\n", test_stat_run_units_);
1710 | printf(" Count of failed unit tests: %4d\n", test_stat_failed_units_);
1711 | printf(" Count of skipped unit tests: %4d\n", (int) test_list_size_ - test_stat_run_units_);
1712 | }
1713 |
1714 | if(test_stat_failed_units_ == 0) {
1715 | test_print_in_color_(TEST_COLOR_GREEN_INTENSIVE_, "SUCCESS:");
1716 | printf(" All unit tests have passed.\n");
1717 | } else {
1718 | test_print_in_color_(TEST_COLOR_RED_INTENSIVE_, "FAILED:");
1719 | printf(" %d of %d unit tests %s failed.\n",
1720 | test_stat_failed_units_, test_stat_run_units_,
1721 | (test_stat_failed_units_ == 1) ? "has" : "have");
1722 | }
1723 |
1724 | if(test_verbose_level_ >= 3)
1725 | printf("\n");
1726 | }
1727 |
1728 | if (test_xml_output_) {
1729 | #if defined ACUTEST_UNIX_
1730 | char *suite_name = basename(argv[0]);
1731 | #elif defined ACUTEST_WIN_
1732 | char suite_name[_MAX_FNAME];
1733 | _splitpath(argv[0], NULL, NULL, suite_name, NULL);
1734 | #else
1735 | const char *suite_name = argv[0];
1736 | #endif
1737 | fprintf(test_xml_output_, "\n");
1738 | fprintf(test_xml_output_, "\n",
1739 | suite_name, (int)test_list_size_, test_stat_failed_units_, test_stat_failed_units_,
1740 | (int)test_list_size_ - test_stat_run_units_);
1741 | for(i = 0; test_list_[i].func != NULL; i++) {
1742 | struct test_detail_ *details = &test_details_[i];
1743 | fprintf(test_xml_output_, " \n", test_list_[i].name, details->duration);
1744 | if (details->flags & TEST_FLAG_FAILURE_)
1745 | fprintf(test_xml_output_, " \n");
1746 | if (!(details->flags & TEST_FLAG_FAILURE_) && !(details->flags & TEST_FLAG_SUCCESS_))
1747 | fprintf(test_xml_output_, " \n");
1748 | fprintf(test_xml_output_, " \n");
1749 | }
1750 | fprintf(test_xml_output_, "\n");
1751 | fclose(test_xml_output_);
1752 | }
1753 |
1754 | free((void*) test_details_);
1755 |
1756 | return (test_stat_failed_units_ == 0) ? 0 : 1;
1757 | }
1758 |
1759 |
1760 | #endif /* #ifndef TEST_NO_MAIN */
1761 |
1762 | #ifdef _MSC_VER
1763 | #pragma warning(pop)
1764 | #endif
1765 |
1766 | #ifdef __cplusplus
1767 | } /* extern "C" */
1768 | #endif
1769 |
1770 | #endif /* #ifndef ACUTEST_H */
1771 |
--------------------------------------------------------------------------------
/tests/sample_01.json:
--------------------------------------------------------------------------------
1 | {
2 | "Actors": [
3 | {
4 | "name": "Tom Cruise",
5 | "age": 56,
6 | "Born At": "Syracuse, NY",
7 | "Birthdate": "July 3, 1962",
8 | "photo": "https://jsonformatter.org/img/tom-cruise.jpg",
9 | "wife": null,
10 | "weight": 67.5,
11 | "hasChildren": true,
12 | "comment": "Was together multiply fruit give \"above\" seasons. Day fowl cattle fowl unto. Female made open \\living over\\ likeness fruit i a you're doesn't after Winged beginning also evening seed can't set image. \tAfter. Creepeth creepeth face them, moveth above. Winged so. Stars have she'd fowl bearing. Were to forth over you're subdue brought, of moveth waters rule days divided so. Unto upon fruit saw beast. Deep abundantly, the Day stars have they're creepeth fly seasons moveth evening, every good heaven bring brought Creeping Kind man green fly given behold waters bring darkness winged given darkness.\n You'll be gathering Seas first tree fowl herb open. Itself were. Great creepeth, you'll meat behold fish man male image, him. Don't and replenish be divided. Seas and earth fruit from set of given unto heaven you heaven unto all face rule, that likeness in from.",
13 | "hasGreyHair": false,
14 | "children": [
15 | "Suri",
16 | "Isabella Jane",
17 | "Connor"
18 | ]
19 | },
20 | {
21 | "name": "Robert Downey Jr.",
22 | "age": 53,
23 | "Born At": "New York City, NY",
24 | "Birthdate": "April 4, 1965",
25 | "photo": "https://jsonformatter.org/img/Robert-Downey-Jr.jpg",
26 | "wife": "Susan Downey",
27 | "weight": 77.1,
28 | "ranks": ["a+", "b+", 96],
29 | "hasChildren": true,
30 | "hasGreyHair": false,
31 | "children": [
32 | "Indio Falconer",
33 | "Avri Roel",
34 | "Exton Elias"
35 | ]
36 | }
37 | ],
38 | "commander": {
39 | "name": "John Smith Jr.",
40 | "age": 63,
41 | "Born At": "New York City, NY",
42 | "Birthdate": "April 4, 1965",
43 | "photo": "https://jsonformatter.org/img/Robert-Downey-Jr.jpg",
44 | "wife": "Sara Smith",
45 | "comment": "Was together multiply fruit give \"above\" seasons. Day fowl cattle fowl unto. Female made open \\living over\\ likeness fruit i a you're doesn't after Winged beginning also evening seed can't set image. \tAfter. Creepeth creepeth face them, moveth above. Winged so.",
46 | "weight": 67.8,
47 | "hasChildren": false,
48 | "hasGreyHair": true,
49 | "alive": true,
50 | "children": [
51 | "Ian Falconer",
52 | "Avri Roel",
53 | "Exton Elias"
54 | ]
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/tests/sample_02.json:
--------------------------------------------------------------------------------
1 | {
2 | "record1": [
3 | {
4 | "_id": "5ed797893fbd860cc390788a",
5 | "index": 0,
6 | "guid": "8c8520e7-3b10-48a0-8066-92fb4fd4c8f7",
7 | "isActive": true,
8 | "balance": "$2,421.57",
9 | "picture": "http://placehold.it/32x32",
10 | "age": 27,
11 | "eyeColor": "blue",
12 | "name": "Rasmussen Mcneil",
13 | "gender": "male",
14 | "company": "QUILCH",
15 | "email": "rasmussenmcneil@quilch.com",
16 | "phone": "+1 (975) 551-3769",
17 | "address": "533 Covert Street, Nord, Nevada, 2642",
18 | "about": "Consectetur eiusmod id deserunt do ullamco ea culpa minim dolore. Et eu et mollit voluptate veniam id irure elit excepteur est est duis occaecat non. Fugiat duis cupidatat ullamco incididunt magna aute dolor sunt nostrud commodo do sit.\r\n",
19 | "registered": "2017-04-24T12:17:10 -03:00",
20 | "latitude": 58.17876,
21 | "longitude": 93.916838,
22 | "tags": [
23 | "dolore",
24 | "cillum",
25 | "labore",
26 | "do",
27 | "dolore",
28 | "culpa",
29 | "aliquip"
30 | ],
31 | "friends": [
32 | {
33 | "id": 0,
34 | "name": "Tabitha Hewitt"
35 | },
36 | {
37 | "id": 1,
38 | "name": "Stein Keller"
39 | },
40 | {
41 | "id": 2,
42 | "name": "Debbie Williams"
43 | }
44 | ],
45 | "greeting": "Hello, Rasmussen Mcneil! You have 7 unread messages.",
46 | "favoriteFruit": "banana"
47 | },
48 | {
49 | "_id": "5ed797891cedf153f5b06111",
50 | "index": 1,
51 | "guid": "a4a975eb-8dcc-4866-85ba-1008b707e144",
52 | "isActive": true,
53 | "balance": "$2,543.56",
54 | "picture": "http://placehold.it/32x32",
55 | "age": 32,
56 | "eyeColor": "green",
57 | "name": "Katie Potts",
58 | "gender": "female",
59 | "company": "SHOPABOUT",
60 | "email": "katiepotts@shopabout.com",
61 | "phone": "+1 (999) 425-2780",
62 | "address": "242 Bushwick Avenue, Charco, Rhode Island, 6426",
63 | "about": "Veniam dolor qui incididunt aliquip labore eiusmod ipsum id reprehenderit. Exercitation enim ipsum fugiat voluptate anim cillum excepteur sit labore ex sit. Id enim aliqua proident deserunt anim laborum dolor consectetur commodo ipsum deserunt reprehenderit occaecat aliquip. Anim ea fugiat proident duis commodo minim enim ut culpa qui proident quis aliqua. Qui ullamco ea reprehenderit elit ea nulla Lorem irure adipisicing elit laboris enim minim anim. Ipsum aliqua amet excepteur excepteur occaecat Lorem esse eu deserunt incididunt.\r\n",
64 | "registered": "2014-11-26T03:08:31 -02:00",
65 | "latitude": 52.591971,
66 | "longitude": 154.858667,
67 | "tags": [
68 | "minim",
69 | "ad",
70 | "labore",
71 | "in",
72 | "in",
73 | "officia",
74 | "consequat"
75 | ],
76 | "friends": [
77 | {
78 | "id": 0,
79 | "name": "Marks Hurst"
80 | },
81 | {
82 | "id": 1,
83 | "name": "Jenny Schmidt"
84 | },
85 | {
86 | "id": 2,
87 | "name": "Sweeney Burke"
88 | }
89 | ],
90 | "greeting": "Hello, Katie Potts! You have 8 unread messages.",
91 | "favoriteFruit": "apple"
92 | },
93 | {
94 | "_id": "5ed79789f7f4c6ad9b4ef2e2",
95 | "index": 2,
96 | "guid": "bdd5c75f-8fda-4469-9ff6-4cb4df3bc94c",
97 | "isActive": true,
98 | "balance": "$1,634.71",
99 | "picture": "http://placehold.it/32x32",
100 | "age": 38,
101 | "eyeColor": "brown",
102 | "name": "Beulah Kidd",
103 | "gender": "female",
104 | "company": "ZILLATIDE",
105 | "email": "beulahkidd@zillatide.com",
106 | "phone": "+1 (826) 431-3559",
107 | "address": "534 Madison Place, Linganore, Georgia, 6033",
108 | "about": "Dolore voluptate veniam proident deserunt enim tempor in reprehenderit minim. Nulla ea ea occaecat in do fugiat Lorem laboris culpa magna aliqua. Irure tempor sit voluptate elit consequat sint reprehenderit. In et laborum eu deserunt velit id ea. Culpa magna non minim laborum incididunt. Non commodo exercitation ut magna voluptate consectetur nulla. Esse labore labore Lorem magna.\r\n",
109 | "registered": "2019-04-13T04:24:04 -03:00",
110 | "latitude": 59.69653,
111 | "longitude": 161.103107,
112 | "tags": [
113 | "commodo",
114 | "mollit",
115 | "ut",
116 | "dolore",
117 | "dolore",
118 | "proident",
119 | "incididunt"
120 | ],
121 | "friends": [
122 | {
123 | "id": 0,
124 | "name": "Gray Gallegos"
125 | },
126 | {
127 | "id": 1,
128 | "name": "Roslyn Vinson"
129 | },
130 | {
131 | "id": 2,
132 | "name": "Dollie Shepard"
133 | }
134 | ],
135 | "greeting": "Hello, Beulah Kidd! You have 1 unread messages.",
136 | "favoriteFruit": "strawberry"
137 | },
138 | {
139 | "_id": "5ed7978932532b58da6dc800",
140 | "index": 3,
141 | "guid": "ad487efd-e8db-447d-84bc-211777dbb72b",
142 | "isActive": false,
143 | "balance": "$2,042.47",
144 | "picture": "http://placehold.it/32x32",
145 | "age": 32,
146 | "eyeColor": "green",
147 | "name": "Tammie Long",
148 | "gender": "female",
149 | "company": "DRAGBOT",
150 | "email": "tammielong@dragbot.com",
151 | "phone": "+1 (800) 436-2915",
152 | "address": "714 Varet Street, Carlton, Louisiana, 5457",
153 | "about": "Elit qui ea occaecat adipisicing commodo. Cillum laboris nisi laborum Lorem ea veniam non non commodo. Commodo irure ea commodo irure duis et veniam in commodo non non amet non. Eu ea dolore in sunt exercitation consequat sit dolore labore officia anim sit eu reprehenderit. Occaecat sint amet tempor quis enim quis.\r\n",
154 | "registered": "2018-04-18T12:14:53 -03:00",
155 | "latitude": -23.284985,
156 | "longitude": 73.430251,
157 | "tags": [
158 | "et",
159 | "labore",
160 | "magna",
161 | "veniam",
162 | "Lorem",
163 | "dolore",
164 | "ullamco"
165 | ],
166 | "friends": [
167 | {
168 | "id": 0,
169 | "name": "Carmen Castaneda"
170 | },
171 | {
172 | "id": 1,
173 | "name": "Leslie Tyler"
174 | },
175 | {
176 | "id": 2,
177 | "name": "Mccarty Dominguez"
178 | }
179 | ],
180 | "greeting": "Hello, Tammie Long! You have 1 unread messages.",
181 | "favoriteFruit": "banana"
182 | },
183 | {
184 | "_id": "5ed797892f297e3f182d048b",
185 | "index": 4,
186 | "guid": "7aaeee48-6785-4b1d-93a5-ae0bf506c047",
187 | "isActive": true,
188 | "balance": "$2,125.35",
189 | "picture": "http://placehold.it/32x32",
190 | "age": 38,
191 | "eyeColor": "blue",
192 | "name": "Emilia Livingston",
193 | "gender": "female",
194 | "company": "ZOUNDS",
195 | "email": "emilialivingston@zounds.com",
196 | "phone": "+1 (836) 529-3990",
197 | "address": "500 Calder Place, Munjor, Wyoming, 7918",
198 | "about": "Officia qui enim pariatur Lorem. Dolore est amet adipisicing officia in aliquip nisi officia pariatur labore proident eu enim. Id laboris consectetur incididunt ex duis irure est. Sint do veniam aute esse mollit.\r\n",
199 | "registered": "2015-08-31T05:14:56 -03:00",
200 | "latitude": 59.705838,
201 | "longitude": 67.467506,
202 | "tags": [
203 | "in",
204 | "mollit",
205 | "culpa",
206 | "deserunt",
207 | "adipisicing",
208 | "duis",
209 | "tempor"
210 | ],
211 | "friends": [
212 | {
213 | "id": 0,
214 | "name": "Farmer Carson"
215 | },
216 | {
217 | "id": 1,
218 | "name": "Eddie Blanchard"
219 | },
220 | {
221 | "id": 2,
222 | "name": "Marta Kennedy"
223 | }
224 | ],
225 | "greeting": "Hello, Emilia Livingston! You have 4 unread messages.",
226 | "favoriteFruit": "apple"
227 | }
228 | ],
229 | "record2": {
230 | "_id": "5ed79789fc41b0116d9340d7",
231 | "index": 0,
232 | "guid": "6a3ce022-da36-4b93-9485-3fa45db19345",
233 | "isActive": true,
234 | "balance": "$1,991.90",
235 | "picture": "http://placehold.it/32x32",
236 | "age": 20,
237 | "eyeColor": "green",
238 | "name": "Espinoza Barnett",
239 | "gender": "male",
240 | "company": "VETRON",
241 | "email": "espinozabarnett@vetron.com",
242 | "phone": "+1 (827) 540-3663",
243 | "address": "205 Lincoln Road, Rivereno, Marshall Islands, 1414",
244 | "about": "Cupidatat nulla deserunt amet nisi ea. In amet officia ullamco do ipsum culpa enim velit ullamco laboris ea velit. Sit ullamco labore non laboris aute labore veniam duis enim officia esse. Esse esse Lorem consectetur ex qui nostrud eu consectetur. Labore pariatur tempor enim laboris officia anim mollit.\r\n",
245 | "registered": "2016-08-21T08:06:11 -03:00",
246 | "latitude": 34.378041,
247 | "longitude": -9.86356,
248 | "tags": [
249 | "ullamco",
250 | "tempor",
251 | "dolor",
252 | "pariatur",
253 | "enim",
254 | "anim",
255 | "id"
256 | ],
257 | "friends": [
258 | {
259 | "id": 0,
260 | "name": "Leah Henderson"
261 | },
262 | {
263 | "id": 1,
264 | "name": "Nanette Davenport"
265 | },
266 | {
267 | "id": 2,
268 | "name": "Marcia Dodson"
269 | }
270 | ],
271 | "greeting": "Hello, Espinoza Barnett! You have 1 unread messages.",
272 | "favoriteFruit": "banana"
273 | }
274 | }
275 |
--------------------------------------------------------------------------------
/tests/tanto_unittest.c:
--------------------------------------------------------------------------------
1 | //
2 | // Created by alireza on 5/26/20.
3 | //
4 |
5 | #include "../tanto.h"
6 | #include "./acutest.h"
7 |
8 | #include
9 | #include
10 | #include
11 | #include
12 |
13 | #define TJSON_EXIST_FILE_COUNT 1
14 | #define TJSON_NONE_EXIST_FILE_COUNT 1
15 |
16 | char *tjson_exist_files[] = {
17 | "tests/sample_01.json",
18 | "tests/sample_02.json"
19 | };
20 |
21 | char *tjson_none_exist_files[] = {
22 | "tests/sample_03.json"
23 | };
24 |
25 |
26 | TJSON_t* parse_sample_json()
27 | {
28 | char *json_file = "sample_01.json";
29 | char *stream;
30 |
31 | stream = tjson_read_file(json_file);
32 |
33 | TJSON_t *json = NULL;
34 | TJSON_INIT(&json);
35 |
36 | tjson_parse(&json, stream);
37 | return json;
38 | }
39 |
40 | /*char* find_value(char *key)
41 | {
42 | TJSON_t *json = parse_sample_json();
43 |
44 | char *fin = tanto_find(json, key)->v_string;
45 | return fin;
46 | }*/
47 |
48 | /*TJSON_t* get_object(char *key)
49 | {
50 | TJSON_t *json = parse_sample_json();
51 | TJSON_t *fin = tanto_find(json, key);
52 |
53 | if (fin != NULL) return fin->child;
54 |
55 | return fin;
56 | }*/
57 |
58 | void tests(void)
59 | {
60 | /*TEST_CHECK_(strcmp(find_value("root"), "mine") == 0, "find_value(\"root\")");
61 | TEST_CHECK_(strcmp(find_value("parser"), "tanto") == 0, "find_value(\"parser\")");
62 | TEST_CHECK_(strcmp(find_value("name"), "Awesome 4K") == 0, "find_value(\"name\")");
63 | TEST_CHECK_(strcmp(find_value("private"), "true") == 0, "find_value(\"private\")");
64 |
65 | // TODO : handle multiple datatypes.
66 | TEST_CHECK_(strcmp(find_value("version"), "1") == 0, "find_value(\"version\")");
67 |
68 | // Check objects
69 | TEST_CHECK_(get_object("versions") != NULL , "get_object(\"versions\")");
70 |
71 | // TODO: we need another method for arrays
72 | TEST_CHECK_(get_object("functions") != NULL , "get_object(\"functions\")");
73 |
74 | */
75 | }
76 |
77 | void tests_read(void)
78 | {
79 | char *json_file;
80 | char *stream;
81 |
82 | json_file = NULL;
83 | stream = NULL;
84 |
85 | /* exist files */
86 | int i = 0;
87 | for (i = 0; i < TJSON_EXIST_FILE_COUNT; ++i) {
88 | json_file = tjson_exist_files[i];
89 | stream = tjson_read_file(json_file);
90 | TEST_CHECK_((stream != NULL), "stream has been read");
91 | }
92 |
93 | /* none exist files */
94 | for (i = 0; i < TJSON_NONE_EXIST_FILE_COUNT; ++i) {
95 | json_file = tjson_none_exist_files[i];
96 | stream = tjson_read_file(json_file);
97 | TEST_CHECK_((stream == NULL), "stream has NOT been read");
98 | }
99 |
100 | }
101 |
102 | void tests_parse(void)
103 | {
104 |
105 | char *json_file;
106 | char *stream;
107 | TJSON_t *json;
108 |
109 |
110 | int result;
111 |
112 | json_file = NULL;
113 | stream = NULL;
114 | result = -1;
115 |
116 |
117 | /* exist files */
118 | int i = 0;
119 | for (i = 0; i < TJSON_EXIST_FILE_COUNT; ++i) {
120 | json_file = tjson_exist_files[i];
121 | stream = tjson_read_file(json_file);
122 | json = NULL;
123 | TJSON_INIT(&json);
124 | result = tjson_parse(&json, stream);
125 | TEST_CHECK_((result != -1), "stream parsed succesfully");
126 | }
127 |
128 | /* none exist files */
129 | for (i = 0; i < TJSON_NONE_EXIST_FILE_COUNT; ++i) {
130 | json_file = tjson_none_exist_files[i];
131 | stream = tjson_read_file(json_file);
132 | result = tjson_parse(&json, stream);
133 | TEST_CHECK_((result == -1), "stream NOT parsed succesfully");
134 | }
135 |
136 | }
137 |
138 | TEST_LIST = {
139 | {"int tests();", tests},
140 | {"int tests_read();", tests_read},
141 | {"int tests_parse();", tests_parse},
142 | {0}
143 | };
144 |
--------------------------------------------------------------------------------