├── .gitignore
├── Implementation.pdf
├── LICENSE
├── README.md
├── User Manual.pdf
├── __init__.py
├── requirements.txt
├── setup.py
├── shaclform
├── __init__.py
├── form2rdf.py
├── generate_form.py
├── rdfhandling
│ └── __init__.py
├── rendering
│ ├── IRI_input.html
│ ├── __init__.py
│ ├── base.html
│ ├── composite_property.html
│ ├── custom_property.html
│ ├── entry.html
│ ├── input_field.html
│ └── property.html
└── webform.js
└── tests
├── __init__.py
├── expected_results
└── empty_shape.html
├── inputs
├── empty_file.ttl
├── empty_shape.ttl
├── implicit_target_class.ttl
├── inclusive_exclusive.ttl
├── invalid_minCount.ttl
├── missing_group.ttl
├── no_path.ttl
├── no_target_class.ttl
├── node_kind
│ ├── blanknode.ttl
│ ├── blanknode_or_iri.ttl
│ ├── blanknode_or_iri_hasvalue.ttl
│ ├── blanknode_or_iri_without_nested_properties.ttl
│ ├── blanknode_or_literal.ttl
│ ├── blanknode_or_literal_hasvalue.ttl
│ ├── blanknode_or_literal_without_nested_properties.ttl
│ ├── blanknode_without_nested_properties.ttl
│ ├── invalid_nodekind_with_hasvalue_constraint.ttl
│ ├── invalid_nodekind_with_nested_properties.ttl
│ ├── invalid_nodekind_without_nested_properties.ttl
│ ├── iri.ttl
│ ├── iri_or_literal.ttl
│ ├── iri_or_literal_hasvalue.ttl
│ ├── iri_or_literal_with_nested_properties.ttl
│ ├── iri_with_nested_properties.ttl
│ ├── literal.ttl
│ ├── literal_with_nested_properties.ttl
│ ├── missing_nodekind_with_hasvalue_constraint.ttl
│ ├── missing_nodekind_with_nested_properties.ttl
│ └── missing_nodekind_without_nested_properties.ttl
├── recursion.ttl
└── test_shape.ttl
├── test_main.py
└── test_rdfhandling.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | env/
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 |
49 | # Translations
50 | *.mo
51 | *.pot
52 |
53 | # Django stuff:
54 | *.log
55 | local_settings.py
56 |
57 | # Flask stuff:
58 | instance/
59 | .webassets-cache
60 |
61 | # Scrapy stuff:
62 | .scrapy
63 |
64 | # Sphinx documentation
65 | docs/_build/
66 |
67 | # PyBuilder
68 | target/
69 |
70 | # Jupyter Notebook
71 | .ipynb_checkpoints
72 |
73 | # pyenv
74 | .python-version
75 |
76 | # celery beat schedule file
77 | celerybeat-schedule
78 |
79 | # SageMath parsed files
80 | *.sage.py
81 |
82 | # dotenv
83 | .env
84 |
85 | # virtualenv
86 | .venv
87 | venv/
88 | ENV/
89 |
90 | # Spyder project settings
91 | .spyderproject
92 | .spyproject
93 |
94 | # Rope project settings
95 | .ropeproject
96 |
97 | # mkdocs documentation
98 | /site
99 |
100 | # mypy
101 | .mypy_cache/
102 |
103 | # Pycharm config
104 | .idea/
105 |
106 | # pytest cach
107 | .pytest_cache/
108 |
109 | # Miniflask
110 | miniflask/.idea/
--------------------------------------------------------------------------------
/Implementation.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CSIRO-enviro-informatics/shacl-form/c2b417f21bb97e2ce47adb710851376f1ced3a7c/Implementation.pdf
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # shacl-form
2 | This repository contains a Python package that generates HTML + JS
3 | webforms from given [W3C](https://www.w3.org/)
4 | [Shapes Constraint Language (SHACL)](https://www.w3.org/TR/shacl/)
5 | "shapes". The intention is to allow for the auto-generation of web UIs,
6 | given only a logical expression of the required data that the UI is to
7 | facilitate the input of. Additionally, this can convert submitted form
8 | data back into RDF format.
9 |
10 | ## License
11 | This work is licensed using the GPL v3 license. See [LICENSE](LICENSE)
12 | for the deed.
13 |
14 | ## Contacts
15 | This work is being conducted by a
16 | [Griffith University](https://griffith.edu.au) Industrial Placement
17 | student at the [CSIRO](https://www.csiro.au).
18 |
19 | **Laura Guillory**
20 | *Lead Developer*
21 | Griffith University Industrial Placement Student at CSIRO Land & Water
22 |
23 |
24 | **Nicholas Car**
25 | *Product Owner*
26 | Senior Experimental Scientist
27 | CSIRO Land & Water
28 |
29 |
30 | ## How to use
31 |
32 | This package is intended to fulfil two main functions - to convert a
33 | SHACL Shapes file into a HTML + JS webform, and to convert form data
34 | back into RDF format.
35 |
36 | Please see the example at
37 | [shacl-form-example](https://github.com/Laura-Guillory/shacl-form-example).
38 |
39 | **Supplying a SHACL shapes file**
40 | A SHACL Shapes file must be supplied to define the data that the form
41 | accommodates. While optional, it is ideal to use the SHACL constraints
42 | sh:name, sh:description and sh:order. These are non-validating SHACL
43 | properties that will improve the appearance of the form.
44 |
45 | This tool is intended to generate a form for only one Shape at a time,
46 | though a Shape may consist of multiple NodeShapes. If multiple
47 | NodeShapes are present in the file, this tool will attempt to determine
48 | which NodeShape is the 'root' Shape. If two unrelated NodeShapes are
49 | present, only one will be present in the form and results may be
50 | inconsistent.
51 |
52 | **Generating the webform**
53 | Use generate_form(). You must supply a Shapes Graph or a file-like
54 | object containing a SHACL Shape in RDF Turtle format. You must also
55 | supply the desired destination for of the HTML form and the RDF map
56 | file.
57 |
58 | It will generate two files:
59 | * `view/templates/form_contents.html` is a Jinja2 template which extends
60 | `form.html.` You will want to edit form.html to control where the form
61 | appears on your site.
62 | * `map.ttl` is a Turtle RDF file which is used to convert information
63 | submitted to the form back into RDF.
64 |
65 | These two files are a pair and can't be interchanged with files
66 | generated for another shape.
67 |
68 | If you want to run this tool from the command line, use:
69 |
70 | python generate_form.py
71 |
72 | **Converting form data**
73 | Use Form2RDFController, supplying the base_uri (which determines the URI
74 | that will be generated for the entries submitted by the form), the
75 | request received from the form, and the path of `map.ttl`.
76 |
77 | It will return an RDF graph containing the data that was submitted to
78 | the form.
79 |
80 | ## Supported constraints
81 |
82 | These constraints are optional unless stated otherwise.
83 |
84 | Each property in a supplied SHACL Shapes file corresponds to one input
85 | field in the resulting webform. Each constraint applied to a property
86 | affects the corresponding input field in the following ways:
87 |
88 | **sh:path**
89 | Determines the HTML name of the input field, and if there is no sh:name,
90 | determines the user-readable label that accompanies the input field. A
91 | required constraint, since the sh:path defines its property in a Shape.
92 |
93 | **sh:nodeKind**
94 | Determines what kind of node the property refers to. Options for
95 | sh:NodeKind are: sh:Literal, sh:IRI, sh:BlankNode, sh:BlankNodeOrIRI,
96 | sh:IRIOrLiteral, sh:BlankNodeOrLiteral
97 |
98 | 1. Literal - Entered as a plain value (for example, a string, number or
99 | date) with constraints applying as normal
100 | 2. IRI - A pattern is applied to ensure the value entered looks like an
101 | IRI, but the validity of the IRI is not checked. An IRI should refer to
102 | a node that already exists. For example, you might want a person to be a
103 | supervisor of another person, so you would enter the IRI of the other
104 | person.
105 | 3. BlankNode - The property will consist of other properties. For
106 | example, an address will be made up of a street name, postcode, country,
107 | etc.
108 | 4. BlankNodeOrIRI - The user can pick between entering a BlankNode or
109 | IRI
110 | 5. IRIOrLiteral - The user can pick between entering an IRI or Literal
111 | 6. BlankNodeOrLiteral - The user can pick between entering a Blank Node
112 | or Literal.
113 |
114 | If the property doesn't fit the specified nodeKind, shacl-form will
115 | provide a warning and the property will look odd/empty.
116 |
117 | **sh:name**
118 | Determines the user-readable label that accompanies the input field.
119 |
120 | **sh:description**
121 | Determines the user-readable description that accompanies the input
122 | field.
123 |
124 | **sh:defaultValue**
125 | Determines the default value of the input field.
126 |
127 | **sh:group**
128 | Determines the group that the input field belongs to. All input fields
129 | belonging to a group will appear together. The group must refer to an
130 | existing Property Group in the SHACL Shapes file. The Property Group may
131 | use rdfs:label to specify the label for the group of properties, and may
132 | use sh:order to specify the order in which groups appear (if there are
133 | multiple groups).
134 |
135 | **sh:order**
136 | Determines the order in which the input fields appear. Also used in
137 | Property Groups to determine the order in which
138 | groups appear. The order is as follows:
139 |
140 | 1. All ordered groups in ascending order
141 | * (Within each group) All ordered properties in ascending order
142 | * (Within each group) All unordered properties
143 |
144 | 2. All unordered groups
145 | * (Within each group) All ordered properties in ascending order
146 | * (Within each group) All unordered properties
147 |
148 | 3. All ungrouped ordered properties in ascending order
149 | 4. All ungrouped unordered properties
150 |
151 | **sh:minCount**
152 | Determines the minimum number of input fields that may be present for
153 | each property.
154 |
155 | **sh:maxCount**
156 | Determines the maximum number of input fields that may be present for
157 | each property.
158 |
159 | **sh:in**
160 | Should supply a list of options. The input field will be a dropdown
161 | containing all the options.
162 |
163 | **sh:datatype**
164 | The datatype will determine the input field type.
165 |
166 | | Datatype | Input Type |
167 | |------------------------------------|------------|
168 | | xsd:integer, xsd:float, xsd:double | number |
169 | | xsd:date | date |
170 | | xsd:time | time |
171 | | xsd:boolean | checkbox |
172 |
173 | Otherwise, it will be of type `text`.
174 |
175 | **sh:minInclusive**
176 | Will set the minimum accepted value of the input field, including the
177 | value provided. The user will not be able to submit values outside the
178 | accepted range.
179 |
180 | **sh:maxExclusive**
181 | Will set the maximum accepted value of the input field, excluding the
182 | value provided. The user will not be able to submit values outside the
183 | accepted range.
184 |
185 | **sh:maxInclusive**
186 | Will set the maximum accepted value of the input field, including the
187 | value provided. The user will not be able to submit values outside the
188 | accepted range.
189 |
190 | **sh:minExclusive**
191 | Will set the minimum accepted value of the input field, excluding the
192 | value provided. The user will not be able to submit values outside the
193 | accepted range.
194 |
195 | **sh:maxlength**
196 | Will set the maximum length of the input field.
197 |
198 | **sh:minLength**
199 | Will set the minimum length of the input field.
200 |
201 | **sh:pattern**
202 | Will set the regex pattern of the input field. Note that a blank field
203 | will still be accepted unless the field is also required. ^ and $ will
204 | be added around the pattern provided.
205 |
206 | **sh:flags**
207 | For use with sh:pattern. The flags set the modifier to be used with the
208 | regex expression. Available flags: m, i
209 |
210 | **sh:hasValue**
211 | This input field will be present when the form is submitted, but will be
212 | hidden from the user.
213 |
214 | **sh:equals**
215 | This input field will be required to equal the referenced property. Note
216 | that unless the field is required, an empty field will be valid.
217 |
218 | **sh:disjoint**
219 | This input field will not be permitted to equal the referenced property.
220 |
221 | **sh:lessThan**
222 | This input field must have a value that is less than the referenced
223 | property.
224 |
225 | **sh:lessThanOrEquals**
226 | This input field must have a value that is less than or equal to the
227 | referenced property.
228 |
229 | **Other**
230 | *foaf:mbox*
231 | If a property requires a foaf:mbox predicate, the corresponding input
232 | field will have input type `email`.
233 |
234 | *foaf:phone*
235 | If a property requires a foaf:phone predicate, the corresponding input
236 | field will have input type `tel`.
237 |
238 | ## Other Features
239 |
240 | **Open/Closed Shapes**
241 | Shapes may have a property of sh:closed.
242 | If sh:closed is True, only properties that are explicitly defined will
243 | be present in the form.
244 | If sh:closed is False, the user will be able to add custom properties in
245 | addition to properties that have been explicitly defined
246 | If sh:closed is absent, it will be assumed that it is equal to False.
247 |
248 | If a Shape is closed, its form will also contain input fields for
249 | properties specified in sh:ignoredProperties.
--------------------------------------------------------------------------------
/User Manual.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CSIRO-enviro-informatics/shacl-form/c2b417f21bb97e2ce47adb710851376f1ced3a7c/User Manual.pdf
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CSIRO-enviro-informatics/shacl-form/c2b417f21bb97e2ce47adb710851376f1ced3a7c/__init__.py
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | pytest
2 | pytest-cov
3 | rdflib
4 | jinja2
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | import setuptools
2 |
3 | with open('README.md', 'r') as fh:
4 | long_description = fh.read()
5 |
6 | setuptools.setup(
7 | name='shaclform',
8 | version='1.0',
9 | author='Laura Guillory',
10 | author_email='laura.guillory@csiro.au',
11 | description='Auto-generation of web UIs, given only a logical expression of the data model as a SHACL shape.',
12 | long_description=long_description,
13 | long_description_content_type='text/markdown',
14 | url='https://github.com/CSIRO-enviro-informatics/shacl-form',
15 | packages=setuptools.find_packages(),
16 | install_requires=['rdflib'],
17 | classifiers=(
18 | 'Programming Language :: Python :: 3',
19 | 'Operating System :: OS Independent',
20 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)'
21 | )
22 | )
23 |
--------------------------------------------------------------------------------
/shaclform/__init__.py:
--------------------------------------------------------------------------------
1 | from shaclform.generate_form import generate_form
2 | from shaclform.form2rdf import Form2RDFController
--------------------------------------------------------------------------------
/shaclform/form2rdf.py:
--------------------------------------------------------------------------------
1 | from rdflib import Graph, RDF, XSD
2 | from rdflib.util import guess_format
3 | from rdflib.term import Literal, URIRef, BNode
4 | import uuid
5 | import re
6 |
7 |
8 | class Form2RDFController:
9 | def __init__(self, base_uri=None, root_node=None):
10 | self.base_uri = base_uri
11 | self.root_node = URIRef(root_node) if root_node else None
12 | if not base_uri and not root_node:
13 | raise ValueError('base_uri or root_node must be provided.')
14 | self.form_input = None
15 | self.rdf_map = None
16 | self.rdf_result = None
17 | self.root_node_class = None
18 |
19 | def convert(self, form_input, map_filename):
20 | self.form_input = form_input.form
21 | # Get map and result RDF graphs ready
22 | self.rdf_map = Graph()
23 | self.rdf_map.parse(map_filename, format=guess_format(map_filename))
24 | self.rdf_result = Graph()
25 | self.rdf_result.namespace_manager = self.rdf_map.namespace_manager
26 | # Find node class
27 | for possible_root_node_class in self.rdf_map.objects(Literal('placeholder node_uri'), URIRef(RDF.type)):
28 | if 'placeholder' not in possible_root_node_class:
29 | self.root_node_class = possible_root_node_class
30 | if self.root_node_class is None:
31 | raise Exception('No root node class specified in ' + map_filename)
32 | # Use provided URI or generate unique URI of the new node
33 | if not self.root_node:
34 | self.root_node = URIRef(self.base_uri + str(uuid.uuid4()))
35 | self.rdf_result.add((self.root_node, RDF.type, self.root_node_class))
36 | # Go through each property and search for entries submitted in the form
37 | for (subject, property_predicate, property_obj) in self.rdf_map:
38 | if str(subject) == 'placeholder node_uri' and 'placeholder' in property_obj:
39 | self.add_entries_for_property(self.root_node, property_predicate, property_obj)
40 | # Also get any custom properties submitted in the form
41 | self.add_custom_property_entries(self.root_node)
42 | return self.rdf_result
43 |
44 | def add_entries_for_property(self, subject, predicate, obj, root_id=None):
45 | """
46 | :param subject: The subject this property will be attached to. It will be the root node unless this is a nested
47 | property
48 | :param predicate: The predicate of the property
49 | :param obj: The object of the property. Can be a literal/IRI or a blank node leading to nested properties
50 | :param root_id: Provides a starting point for building nested property IDs used to get an entry in the form
51 | :return:
52 | """
53 | if not root_id:
54 | root_id = obj.split(' ')[-1]
55 | copy_id = 0
56 | found_at_least_one_entry = False
57 | # Cycles through entries by ID until no more entries are found
58 | while True:
59 | # Every entry for this property shares a root_id, and has a different copy_id
60 | entry_id = root_id + '-' + str(copy_id)
61 | m = re.search('nodeKind=(\w+)', obj)
62 | if m is None:
63 | raise ValueError('No nodeKind option provided: ' + obj)
64 | permitted_node_kind = m.group().split('=')[1]
65 | node_kind_selection = self.get_node_kind_selection(permitted_node_kind, entry_id)
66 | if node_kind_selection == 'BlankNode':
67 | if self.add_blank_node_entry(subject, predicate, obj, entry_id):
68 | found_at_least_one_entry = True
69 | copy_id += 1
70 | else:
71 | break
72 | elif node_kind_selection == 'IRI':
73 | if self.add_iri_entry(subject, predicate, entry_id):
74 | found_at_least_one_entry = True
75 | copy_id += 1
76 | else:
77 | break
78 | elif node_kind_selection == 'Literal':
79 | if self.add_literal_entry(subject, predicate, obj, entry_id):
80 | found_at_least_one_entry = True
81 | copy_id += 1
82 | else:
83 | break
84 | else:
85 | break
86 | return found_at_least_one_entry
87 |
88 | def get_node_kind_selection(self, permitted_node_kind, entry_id):
89 | # Selection isn't necessary if the nodeKind is specified as one of these
90 | if permitted_node_kind in ['Literal', 'IRI', 'BlankNode']:
91 | return permitted_node_kind
92 | # The permitted nodeKind should be one of these
93 | if permitted_node_kind not in ['BlankNodeOrIRI', 'BlankNodeOrLiteral', 'IRIOrLiteral']:
94 | raise ValueError('Not valid nodeKind option: ' + permitted_node_kind)
95 | # Get the options that the user can select from
96 | node_kind_options = permitted_node_kind.split('Or')
97 | # Get user selection for node kind for this entry
98 | node_kind_id = 'NodeKind ' + entry_id
99 | node_kind_selection = self.form_input.get(node_kind_id)
100 | if not node_kind_selection:
101 | return None
102 | # Check the user selected one of the options
103 | if node_kind_selection not in node_kind_options:
104 | raise ValueError('Not valid nodeKind selection: ' + node_kind_selection)
105 | return node_kind_selection
106 |
107 | def add_literal_entry(self, subject, predicate, obj, entry_id):
108 | entry = self.form_input.get(entry_id)
109 | m = re.search('datatype=[^ ]*', obj)
110 | if m is None:
111 | datatype = None
112 | else:
113 | datatype = m.group().split('=')[1]
114 | if datatype == XSD.boolean:
115 | # Unchecked checkboxes in a form aren't submitted with the form
116 | # Form has been altered to submit hidden field with prefix 'Unchecked ' if a checkbox isn't checked
117 | # Normal entry -> True
118 | if entry:
119 | self.rdf_result.add((subject, predicate, Literal(True, datatype=XSD.boolean)))
120 | return True
121 | # Entry with prefix 'Unchecked ' -> False
122 | elif self.form_input.get('Unchecked ' + entry_id):
123 | self.rdf_result.add((subject, predicate, Literal(False, datatype=XSD.boolean)))
124 | return True
125 | # Neither -> No value
126 | else:
127 | return False
128 | elif entry:
129 | self.rdf_result.add((subject, predicate, Literal(entry, datatype=datatype)))
130 | return True
131 | return False
132 |
133 | def add_iri_entry(self, subject, predicate, entry_id):
134 | entry = self.form_input.get(entry_id)
135 | if entry:
136 | self.rdf_result.add((subject, predicate, URIRef(self.validate_iri(entry))))
137 | return True
138 | else:
139 | return False
140 |
141 | def add_blank_node_entry(self, subject, predicate, obj, entry_id):
142 | node = BNode()
143 | included_properties = list(self.rdf_map.predicate_objects(obj))
144 | found_entry = False
145 | for p in included_properties:
146 | nested_property_id = entry_id + ':' + p[1].split(':')[-1]
147 | found_entry_for_property = self.add_entries_for_property(node, p[0], p[1], nested_property_id)
148 | if found_entry_for_property:
149 | found_entry = True
150 | if found_entry:
151 | self.rdf_result.add((subject, predicate, node))
152 | return True
153 | else:
154 | return False
155 |
156 | def add_custom_property_entries(self, root_node):
157 | copy_id = 0
158 | # Cycles through entries by ID until no more entries are found
159 | while True:
160 | predicate_id = 'Predicate CustomProperty-' + str(copy_id)
161 | predicate = self.form_input.get(predicate_id)
162 | type_selection_id = 'Object Type CustomProperty-' + str(copy_id)
163 | type_selection = self.form_input.get(type_selection_id)
164 | obj_id = 'Object CustomProperty-' + str(copy_id)
165 | obj = self.form_input.get(obj_id)
166 | if predicate is None or type_selection is None or obj is None:
167 | break
168 | predicate = URIRef(self.validate_iri(predicate))
169 | if type_selection == 'IRI':
170 | obj = URIRef(self.validate_iri(obj))
171 | elif type_selection == 'Boolean':
172 | if obj == 'True' or obj == 'true' or obj == '1':
173 | obj = Literal(obj, datatype=XSD.boolean)
174 | else:
175 | obj = Literal(obj, datatype=XSD.string)
176 | self.rdf_result.add((root_node, predicate, obj))
177 | copy_id += 1
178 |
179 | @staticmethod
180 | def validate_iri(iri):
181 | if iri is None:
182 | return
183 | # Remove enclosing <>
184 | if iri.startswith('<'):
185 | iri = iri.strip('<>')
186 | # Ensure URI is valid
187 | for char in '<>" {}|\\^`':
188 | if char in iri: # Invalid URI
189 | raise ValueError('Invalid URI: ' + iri)
190 | return iri
191 |
--------------------------------------------------------------------------------
/shaclform/generate_form.py:
--------------------------------------------------------------------------------
1 | from shaclform.rdfhandling import RDFHandler
2 | import sys
3 | from shaclform.rendering import render_template
4 | import os
5 | import re
6 |
7 |
8 | def generate_form(shape, form_destination='../miniflask/view/templates/form_contents.html',
9 | map_destination='../miniflask/map.ttl'):
10 | """
11 | :param shape: An RDF Graph or a file-like object that can be read.
12 | :param form_destination: Where the HTML file containing the form should be placed
13 | :param map_destination: Where the Turtle file containing the Shape RDF map should be placed
14 | :return:
15 | """
16 | # Get shape
17 | rdf_handler = RDFHandler(shape)
18 | shape = rdf_handler.get_shape()
19 |
20 | # Check that the file contained a shape
21 | if not shape:
22 | raise Exception('No shape provided.')
23 |
24 | # Get a name for the form by cutting off part of the target class URI to find a more human readable name
25 | # Example: http://schema.org/Person -> Person
26 | form_name = shape['target_class'].rsplit('/', 1)[1] if 'target_class' in shape else 'Entry'
27 |
28 | # Add ignored properties
29 | if 'ignoredProperties' in shape:
30 | for ignored_property_path in shape['ignoredProperties']:
31 | ignored_property = {
32 | 'path': ignored_property_path,
33 | 'name': re.split('[#/]', ignored_property_path)[-1],
34 | 'order': None,
35 | 'nodeKind': 'http://www.w3.org/ns/shacl#IRIOrLiteral'
36 | }
37 | shape['properties'].append(ignored_property)
38 |
39 | # Sort the groups
40 | shape['groups'] = sort_by_order(shape['groups'])
41 | # Sort properties in groups
42 | for g in shape['groups']:
43 | g['properties'] = sort_by_order(g['properties'])
44 | for prop in g['properties']:
45 | sort_composite_property(prop)
46 | # Sort ungrouped properties
47 | shape['properties'] = sort_by_order(shape['properties'])
48 | for prop in shape['properties']:
49 | sort_composite_property(prop)
50 |
51 | # Assign every property a unique ID
52 | next_id = 0
53 | for g in shape['groups']:
54 | for prop in g['properties']:
55 | assign_id(prop, next_id)
56 | next_id += 1
57 | for prop in shape['properties']:
58 | assign_id(prop, next_id)
59 | next_id += 1
60 |
61 | # Link pair property constraints by ID
62 | for g in shape["groups"]:
63 | for prop in g["properties"]:
64 | for constraint in prop:
65 | find_paired_properties(shape, prop, constraint)
66 | for prop in shape["properties"]:
67 | for constraint in prop:
68 | find_paired_properties(shape, prop, constraint)
69 |
70 | # Put things into template
71 | os.makedirs(os.path.dirname(os.path.abspath(form_destination)), exist_ok=True)
72 | with open(form_destination, 'w') as file:
73 | file.write(render_template(form_name, shape))
74 |
75 | # Create map for converting submitted data into RDF
76 | rdf_handler.create_rdf_map(shape, map_destination)
77 |
78 |
79 | def sort_by_order(properties):
80 | """
81 | This lambda expression uses a tuple to sort items with an order before unordered items. Tuples are compared by their
82 | first element first, then the second, etc. False sorts before True, so all None values will be sorted to the end
83 | """
84 | properties.sort(key=lambda x: (x['order'] is None, x['order']))
85 | return properties
86 |
87 |
88 | def sort_composite_property(prop):
89 | if 'property' in prop:
90 | prop['property'] = sort_by_order(prop['property'])
91 | for p in prop['property']:
92 | sort_composite_property(p)
93 |
94 |
95 | def assign_id(prop, next_id, parent_id=None):
96 | # Assigns the property an ID
97 | # Additionally, assigns an ID to any property within this property
98 | if parent_id is not None:
99 | prop["id"] = str(parent_id) + ":" + str(next_id)
100 | else:
101 | prop["id"] = next_id
102 | if "property" in prop:
103 | next_internal_id = 0
104 | for p in prop["property"]:
105 | assign_id(p, next_internal_id, parent_id=prop["id"])
106 | next_internal_id += 1
107 |
108 |
109 | def find_paired_properties(shape, prop, constraint):
110 | # If the constraint is a pair property constraint, iterates through all the properties looking for the one that
111 | # matches
112 | # Additionally, looks for pair property constraints in the properties contained in this property using recursion
113 | if constraint == "property":
114 | for p in prop[constraint]:
115 | for c in p:
116 | find_paired_properties(shape, p, c)
117 | if constraint in ["equals", "disjoint", "lessThan", "lessThanOrEquals"]:
118 | for g in shape["groups"]:
119 | for p in g["properties"]:
120 | result = check_property(p, prop[constraint])
121 | if result is not None:
122 | prop[constraint] = result
123 | return
124 | for p in shape["properties"]:
125 | result = check_property(p, prop[constraint])
126 | if result is not None:
127 | prop[constraint] = result
128 | return
129 |
130 |
131 | def check_property(prop, path):
132 | # If the property path matches the path being searched for, return the property id
133 | # Also searches the properties inside this property using recursion
134 | if prop["path"] == path:
135 | return prop["id"]
136 | if "property" in prop:
137 | for p in prop["property"]:
138 | result = check_property(p, path)
139 | if result is not None:
140 | return result
141 |
142 |
143 | if __name__ == "__main__":
144 | # File name passed as command-line argument
145 | if len(sys.argv) < 2:
146 | raise Exception('Usage - python main.py '
147 | '= 4:
152 | with open(file_path) as f:
153 | generate_form(f, sys.argv[2], sys.argv[3])
154 | elif len(sys.argv) >= 2:
155 | with open(file_path) as f:
156 | generate_form(f)
157 |
--------------------------------------------------------------------------------
/shaclform/rdfhandling/__init__.py:
--------------------------------------------------------------------------------
1 | from rdflib.graph import Graph
2 | from rdflib.term import URIRef, Literal
3 | from rdflib.util import guess_format
4 | from rdflib.collection import Collection
5 | from rdflib.namespace import RDF, RDFS
6 | from warnings import warn
7 | import re
8 |
9 | SHACL = 'http://www.w3.org/ns/shacl#'
10 |
11 |
12 | class RDFHandler:
13 | """
14 | Reads information from a SHACL Shapes file.
15 | For each shape, can determine:
16 | Shape URI
17 | Target class
18 | Properties associated with the shape
19 | """
20 | def __init__(self, shape):
21 | self.g = Graph()
22 | if type(shape) is Graph:
23 | self.g = shape
24 | else:
25 | self.g.parse(shape, format=guess_format(shape.name))
26 | shape.close()
27 |
28 | def get_shape(self):
29 | # Will hold the target class, groups, and ungrouped properties
30 | shape = dict()
31 |
32 | """
33 | First, get the root shape. The only shapes we are interested in are Node Shapes. They define all the properties
34 | and constraints relating to a node that we want to create a form for. Property shapes are useful for defining
35 | constraints, but are not relevant here
36 |
37 | Shapes which match this criteria are subjects of a triple with a predicate of rdf:type and an object of
38 | sh:NodeShape
39 |
40 | Shapes and properties can reference other shapes using the sh:node predicate. Therefore, the root shape is the
41 | only shape that is not the object of a triple with a predicate of sh:node.
42 | """
43 | shape_uris = list(self.g.subjects(URIRef(RDF.uri + 'type'), URIRef(SHACL + 'NodeShape')))
44 | root_uri = None
45 | if not shape_uris:
46 | return None
47 | for s in shape_uris:
48 | if (None, URIRef(SHACL + 'node'), s) not in self.g:
49 | root_uri = s
50 | break
51 | if not root_uri:
52 | raise Exception('Recursion not allowed.')
53 |
54 | """
55 | Add any nodes which may be attached to this root shape.
56 | Does this by grabbing everything in that node and adding it to the root shape.
57 | Nodes inside properties are handled in get_property
58 | """
59 | nodes = self.g.objects(root_uri, URIRef(SHACL + 'node'))
60 | for n in nodes:
61 | for (p, o) in self.g.predicate_objects(n):
62 | self.add_node(root_uri, p, o)
63 |
64 | """
65 | Get the target class
66 | Node Shapes have 0-1 target classes. The target class is useful for naming the form.
67 | Looks for implicit class targets - a shape of type sh:NodeShape and rdfs:Class is a target class of itself.
68 | """
69 | if (root_uri, URIRef(RDF.uri + 'type'), URIRef(RDFS.uri + 'Class')) in self.g:
70 | shape['target_class'] = root_uri
71 | else:
72 | shape['target_class'] = self.g.value(root_uri, URIRef(SHACL + 'targetClass'), None)
73 | if not shape['target_class']:
74 | raise Exception('A target class must be specified for shape: ' + root_uri)
75 |
76 | """
77 | Get the closed status
78 | Shapes which are open allow the presence of properties not explicitly defined in the shape
79 | Shapes which are closed will only allow explicitly defined properties
80 | """
81 | is_closed = self.g.value(root_uri, URIRef(SHACL + 'closed'), None)
82 | if is_closed is None:
83 | shape['closed'] = False
84 | else:
85 | shape['closed'] = is_closed.toPython()
86 |
87 | """
88 | If the shape is closed, get the ignored properties. These properties will be allowed despite the shape
89 | being closed and not being defined in their own property shape.
90 | """
91 | if 'closed' in shape and shape['closed'] is True:
92 | ignored_properties = self.g.value(root_uri, URIRef(SHACL + 'ignoredProperties'))
93 | if ignored_properties:
94 | shape['ignoredProperties'] = [str(l) for l in list(Collection(self.g, ignored_properties))]
95 |
96 | """
97 | Get the groups
98 | Some properties belong to groups which determine how they are presented in the form.
99 | """
100 | shape['groups'] = list()
101 | group_uris = self.g.subjects(URIRef(RDF.uri + 'type'), URIRef(SHACL + 'PropertyGroup'))
102 | for g_uri in group_uris:
103 | group = dict()
104 | group['uri'] = g_uri
105 | group['label'] = self.g.value(g_uri, URIRef(RDFS.uri + 'label'), None)
106 | group['order'] = self.g.value(g_uri, URIRef(SHACL + 'order'), None)
107 | group['properties'] = list()
108 | shape['groups'].append(group)
109 |
110 | """
111 | Get all the properties associated with the Shape. They may be URIs or blank nodes. Additional shapes may be
112 | linked as a node.
113 | If it belongs to a group, place it in the list of properties associated with the group
114 | Otherwise, place it in the list of ungrouped properties
115 | """
116 | shape['properties'] = list()
117 | property_uris = list(self.g.objects(root_uri, URIRef(SHACL + 'property')))
118 | for p_uri in property_uris:
119 | prop = self.get_property(p_uri)
120 | # Place the property in the correct place
121 | group_uri = self.g.value(p_uri, URIRef(SHACL + 'group'), None)
122 | # Belongs to group
123 | if group_uri:
124 | # Check if the group referenced actually exists
125 | existing_group = None
126 | for g in shape['groups']:
127 | if g['uri'] == group_uri:
128 | existing_group = g
129 | if existing_group:
130 | existing_group['properties'].append(prop)
131 | else:
132 | raise Exception('Property ' + p_uri + ' references PropertyGroup ' + group_uri
133 | + ' which does not exist.')
134 | # Does not belong to a group
135 | else:
136 | shape['properties'].append(prop)
137 | return shape
138 |
139 | def get_property(self, uri, path_required=True):
140 | prop = dict()
141 | c_uris = list(self.g.predicate_objects(uri))
142 |
143 | # Link nodes
144 | for c_uri in tuple(c_uris):
145 | if re.split('[#/]', c_uri[0])[-1] == 'node':
146 | c_uris.extend(self.g.predicate_objects(c_uri[1]))
147 |
148 | # Go through each constraint and convert/validate them as necessary
149 | for c_uri in c_uris:
150 | name = re.split('[#/]', c_uri[0])[-1]
151 | value = c_uri[1]
152 |
153 | # Get list of values from constraints that supply a list
154 | if name in ['in', 'languageIn']:
155 | value = [str(l) for l in list(Collection(self.g, value))]
156 | # Convert constraints which must be given as an int
157 | elif name in ['minCount', 'maxCount']:
158 | try:
159 | value = int(value)
160 | except ValueError:
161 | raise Exception(
162 | name + ' value must be an integer: "{value}"'.format(value=value))
163 | # Convert constraints which must be converted from an rdf literal
164 | elif name in ['hasValue', 'defaultValue']:
165 | value = value.toPython()
166 | # Some properties are made up of other properties
167 | # Handle this with recursion
168 | elif name == 'property':
169 | if 'property' in prop:
170 | properties = prop['property']
171 | properties.append(self.get_property(value))
172 | value = properties
173 | else:
174 | value = [self.get_property(value)]
175 | # Consolidate constraints which may be supplied in different ways
176 | # minInclusive and minExclusive can be simplified down to one attribute
177 | elif name in ['minInclusive', 'minExclusive', 'maxInclusive', 'maxExclusive']:
178 | if name == 'minInclusive':
179 | name = 'min'
180 | value = float(value)
181 | elif name == 'minExclusive':
182 | name = 'min'
183 | value = float(value) + 1
184 | if name == 'maxInclusive':
185 | name = 'max'
186 | value = float(value)
187 | elif name == 'maxExclusive':
188 | name = 'max'
189 | value = float(value) - 1
190 | # All other constraints should be converted to strings
191 | else:
192 | value = str(value)
193 |
194 | prop[name] = value
195 |
196 | # Validate property as a whole
197 | # Property must have one and only one path
198 | if 'path' not in prop and path_required:
199 | raise Exception('Every property must have a path associated with it: ' + uri)
200 |
201 | # Must have a name
202 | # If the property doesn't have a name label, fall back to the URI of the path.
203 | if 'name' not in prop and 'path' in prop:
204 | prop['name'] = re.split('[#/]', prop['path'])[-1]
205 |
206 | # There must be an entry for order even if it is unordered
207 | if 'order' not in prop:
208 | prop['order'] = None
209 |
210 | # If sh:nodeKind is not present, an appropriate option will be guessed
211 | # If nested properties are present -> sh:BlankNodeOrIRI
212 | # Otherwise -> sh:IRIOrLiteral
213 | warning = None
214 | if 'nodeKind' not in prop:
215 | if 'hasValue' in prop:
216 | prop['nodeKind'] = SHACL + 'Literal'
217 | else:
218 | prop['nodeKind'] = SHACL + 'BlankNodeOrIRI' if 'property' in prop else SHACL + 'IRIOrLiteral'
219 | elif prop['nodeKind'] not in [SHACL + 'BlankNode', SHACL + 'IRI', SHACL + 'Literal',
220 | SHACL + 'BlankNodeOrIRI', SHACL + 'BlankNodeOrLiteral',
221 | SHACL + 'IRIOrLiteral']:
222 | if 'hasValue' in prop:
223 | default_value = SHACL + 'Literal'
224 | else:
225 | default_value = SHACL + 'BlankNodeOrIRI' if 'property' in prop else SHACL + 'IRIOrLiteral'
226 | warning = 'Property "' + prop['name'] + '" has constraint "sh:nodeKind" with invalid value "' + \
227 | prop['nodeKind'] + '". Replacing with "' + default_value + '".'
228 | prop['nodeKind'] = default_value
229 | # Make sure there is enough information provided to accommodate the selected option
230 | else:
231 | # If sh:hasValue is present, the user won't be able to choose between nodeKinds, therefore sh:nodeKind can't
232 | # be BlankNodeOrIRI, IRIOrLiteral, or BlankNodeOrLiteral
233 | if 'hasValue' in prop and prop['nodeKind'] in [SHACL + 'BlankNodeOrIRI', SHACL + 'IRIOrLiteral',
234 | SHACL + 'BlankNodeOrLiteral']:
235 | if prop['nodeKind'] == SHACL + 'BlankNodeOrIRI':
236 | new_node_kind = SHACL + 'IRI'
237 | elif prop['nodeKind'] == SHACL + 'IRIOrLiteral':
238 | new_node_kind = SHACL + 'Literal'
239 | elif prop['nodeKind'] == SHACL + 'BlankNodeOrLiteral':
240 | new_node_kind = SHACL + 'Literal'
241 | warning = 'Property "' + prop['name'] + '" has constraint "sh:nodeKind" with value "' + \
242 | prop['nodeKind'] + '" which is incompatible with constraint sh:hasValue. Replacing ' \
243 | 'with "' + new_node_kind + '".'
244 | prop['nodeKind'] = new_node_kind
245 | # If sh:BlankNode is selected, nested properties should be provided.
246 | if prop['nodeKind'] == SHACL + 'BlankNode' and 'property' not in prop:
247 | warning = 'Property "' + prop['name'] + '" has constraint "sh:nodeKind" with value "sh:BlankNode" but' \
248 | ' no property shapes are provided. This property will have no input fields.'
249 | # If sh:BlankNodeOrIRI or sh:BlankNodeOrLiteral are selected, nested properties should be provided for the
250 | # blank node option
251 | elif prop['nodeKind'] in [SHACL + 'BlankNodeOrIRI', SHACL + 'BlankNodeOrLiteral'] \
252 | and 'property' not in prop:
253 | warning = 'Property "' + prop['name'] + '" has constraint "sh:nodeKind" with value "' + \
254 | prop['nodeKind'] + '" but no property shapes are provided. If the user selects the ' \
255 | '"blank node" option, this property will have no input fields.'
256 | # If sh:IRI, sh:Literal, or sh:IRIOrLiteral are selected, nested properties will be ignored.
257 | elif prop['nodeKind'] in [SHACL + 'Literal', SHACL + 'IRI', SHACL + 'IRIOrLiteral'] and 'property' in prop:
258 | warning = 'Property "' + prop['name'] + '" has constraint "sh:nodeKind" with value "' + \
259 | prop['nodeKind'] + '". The property shapes provided in this property will be ignored.'
260 | if warning:
261 | warn(warning)
262 | return prop
263 |
264 | def add_node(self, root_uri, predicate, obj):
265 | # Adds the contents of the node to the root shape
266 | # If the node contains a link to another node, use recursion to add nodes at all depths
267 | if str(predicate) == SHACL + 'node':
268 | for (p, o) in self.g.predicate_objects(obj):
269 | self.add_node(root_uri, p, o)
270 | self.g.add((root_uri, predicate, obj))
271 |
272 | def create_rdf_map(self, shape, destination):
273 | g = Graph()
274 | g.namespace_manager = self.g.namespace_manager
275 | g.bind('sh', SHACL)
276 | # Create the node associated with all the data entered
277 | g.add((Literal('placeholder node_uri'), RDF.type, shape['target_class']))
278 | # Go through each property and add it
279 | for group in shape['groups']:
280 | for prop in group['properties']:
281 | self.add_property_to_map(g, prop, Literal('placeholder node_uri'))
282 | for prop in shape['properties']:
283 | self.add_property_to_map(g, prop, Literal('placeholder node_uri'))
284 | g.serialize(destination=destination, format='turtle')
285 |
286 | def add_property_to_map(self, graph, prop, root):
287 | # Recursive
288 | arguments = 'nodeKind=' + re.split('[#/]', prop['nodeKind'])[-1]
289 | if 'datatype' in prop:
290 | arguments = arguments + ' datatype=' + prop['datatype']
291 | placeholder = 'placeholder ' + arguments + ' ' + str(prop['id'])
292 | graph.add((root, URIRef(prop['path']), Literal(placeholder)))
293 | if 'property' in prop:
294 | for p in prop['property']:
295 | self.add_property_to_map(graph, p, Literal(placeholder))
296 |
--------------------------------------------------------------------------------
/shaclform/rendering/IRI_input.html:
--------------------------------------------------------------------------------
1 | {%- if 'in' in property %}
2 |
27 | {%- else %}
28 |
51 | {%- endif %}
--------------------------------------------------------------------------------
/shaclform/rendering/__init__.py:
--------------------------------------------------------------------------------
1 | import os
2 | from jinja2 import FileSystemLoader, Environment
3 |
4 | URIs = {
5 | 'NUMBER': [
6 | 'http://www.w3.org/2001/XMLSchema#integer',
7 | 'http://www.w3.org/2001/XMLSchema#float',
8 | 'http://www.w3.org/2001/XMLSchema#double',
9 | 'http://www.w3.org/2001/XMLSchema#decimal'
10 | ],
11 | 'EMAIL': 'http://xmlns.com/foaf/0.1/mbox',
12 | 'DATE': 'http://www.w3.org/2001/XMLSchema#date',
13 | 'PHONE_NUMBER': 'http://xmlns.com/foaf/0.1/phone',
14 | 'TIME': 'http://www.w3.org/2001/XMLSchema#time',
15 | 'BOOLEAN': 'http://www.w3.org/2001/XMLSchema#boolean',
16 | 'STRING': 'http://www.w3.org/2001/XMLSchema#string',
17 | 'BLANK_NODE': 'http://www.w3.org/ns/shacl#BlankNode',
18 | 'IRI': 'http://www.w3.org/ns/shacl#IRI',
19 | 'LITERAL': 'http://www.w3.org/ns/shacl#Literal',
20 | 'BLANK_NODE_OR_IRI': 'http://www.w3.org/ns/shacl#BlankNodeOrIRI',
21 | 'BLANK_NODE_OR_LITERAL': 'http://www.w3.org/ns/shacl#BlankNodeOrLiteral',
22 | 'IRI_OR_LITERAL': 'http://www.w3.org/ns/shacl#IRIOrLiteral'
23 | }
24 |
25 |
26 | def render_template(form_name, shape):
27 | loader = FileSystemLoader(searchpath=os.path.dirname(__file__))
28 | env = Environment(loader=loader)
29 | template = env.get_template('base.html')
30 | return template.render(form_name=form_name, shape=shape, URIs=URIs)
31 |
--------------------------------------------------------------------------------
/shaclform/rendering/base.html:
--------------------------------------------------------------------------------
1 | {%- macro display_property(property) %}
2 | {%- include 'property.html' %}
3 | {%- endmacro -%}
4 | {%- macro custom_property() %}
5 | {%- include 'custom_property.html' %}
6 | {%- endmacro -%}
7 | {{ '{% extends "form.html" %}' }}
8 | {{ '{% block form_heading %}' }}Create New {{ form_name }}{{ '{% endblock %}' }}
9 | {{ '{% block form_contents %}' }}
10 | {%- for group in shape['groups'] %}
11 |
17 | {%- endfor %}
18 | {%- for property in shape['properties'] %}
19 | {{- display_property(property) }}
20 | {%- endfor %}
21 | {%- if 'closed' not in shape or shape['closed'] == false %}
22 |
26 | {%- endif %}
27 | {{ '{% endblock %}' }}
28 | {{ '{% block prefill %}' }}
29 | {{ '' }}
30 | {{ '{% endblock %}' }}
--------------------------------------------------------------------------------
/shaclform/rendering/composite_property.html:
--------------------------------------------------------------------------------
1 | {%- macro display_property(property, disabled=False) %}
2 | {%- include 'property.html' %}
3 | {%- endmacro -%}
4 |
5 |
--------------------------------------------------------------------------------
/shaclform/rendering/custom_property.html:
--------------------------------------------------------------------------------
1 |
32 |
33 | {%- if 'maxCount' not in property or property['maxCount'] != 1 or 'minCount' not in property or property['minCount'] != 1 %}
34 |
35 | {%- endif %}
36 |
37 | {%- endif %}
--------------------------------------------------------------------------------
/shaclform/webform.js:
--------------------------------------------------------------------------------
1 | // Using val() on a checkbox always returns 'on' regardless of its actual value
2 | // This function returns the correct value of an input without having to check for a checkbox every time
3 | jQuery.fn.getValue = function() {
4 | if ($(this).attr('type') == 'checkbox')
5 | return $(this).is(':checked');
6 | else
7 | return $(this).val();
8 | }
9 |
10 | // To set the value of any input field or select field
11 | jQuery.fn.setValue = function(value) {
12 | if ($(this).attr('type') == 'checkbox')
13 | $(this).prop('checked', value).change()
14 | else if ($(this).is('select'))
15 | $(this).children('[value="' + value + '"]').prop('selected', true).change()
16 | else if ($(this).attr('type') == 'radio')
17 | $(this).siblings(':radio[value="' + value + '"]').first().prop('checked', true).change()
18 | else
19 | $(this).val(value).change()
20 | return this
21 | }
22 |
23 | //Custom rules that can be used with any input type
24 | $.validator.addMethod('data-equalTo', function(value, element, params) {
25 | var subject_value;
26 | var object_value;
27 | var object = $('[data-property-id=' + params + ']:not([disabled])');
28 | if (object.length == 0) return true;
29 | subject_value = $(element).getValue();
30 | object_value = $(object).getValue();
31 | if ($(element).attr('type') == 'checkbox')
32 | return subject_value == object_value;
33 | else
34 | return this.optional(element) || subject_value == object_value;
35 | }, function(params, element) {
36 | return $.validator.format(
37 | 'Must be equal to {0} ({1})',
38 | $('[data-property-id=' + $(element).attr('data-equalTo') + ']').attr('data-label'),
39 | $('[data-property-id=' + $(element).attr('data-equalTo') + ']').getValue()
40 | );
41 | });
42 | $.validator.addMethod('data-notEqualTo', function(value, element, params) {
43 | var subject_value;
44 | var object_value;
45 | var object = $('[data-property-id=' + params + ']:not([disabled])');
46 | if (object.length == 0) return true;
47 | subject_value = $(element).getValue();
48 | object_value = $(object).getValue();
49 | return this.optional(element) || subject_value != object_value;
50 | }, function(params, element) {
51 | return $.validator.format(
52 | 'Must not be equal to {0} ({1})',
53 | $('[data-property-id=' + $(element).attr('data-notEqualTo') + ']').attr('data-label'),
54 | $('[data-property-id=' + $(element).attr('data-notEqualTo') + ']').getValue()
55 | );
56 | });
57 | $.validator.addMethod('lessThan', function(value, element, params) {
58 | var subject_value;
59 | var object_value;
60 | var object = $('[data-property-id=' + params + ']:not([disabled])');
61 | if (object.length == 0) return true;
62 | subject_value = $(element).getValue();
63 | object_value = $(object).getValue();
64 | return this.optional(element) || subject_value < object_value;
65 | }, function(params, element) {
66 | return $.validator.format(
67 | 'Must be less than {0} ({1})',
68 | $('[data-property-id=' + $(element).attr('lessThan') + ']').attr('data-label'),
69 | $('[data-property-id=' + $(element).attr('lessThan') + ']').getValue()
70 | );
71 | });
72 | $.validator.addMethod('data-lessThanEqual', function(value, element, params) {
73 | var subject_value;
74 | var object_value;
75 | var object = $('[data-property-id=' + params + ']:not([disabled])');
76 | if (object.length == 0) return true;
77 | subject_value = $(element).getValue();
78 | object_value = $(object).getValue();
79 | return this.optional(element) || subject_value <= object_value;
80 | }, function(params, element) {
81 | return $.validator.format(
82 | 'Must be less than or equal to {0} ({1})',
83 | $('[data-property-id=' + $(element).attr('data-lessThanEqual') + ']').attr('data-label'),
84 | $('[data-property-id=' + $(element).attr('data-lessThanEqual') + ']').getValue()
85 | );
86 | } );
87 |
88 | // Used to automatically add custom rules to relevant elements. Disabled fields are not validated
89 | $('#shacl-form').validate({
90 | ignore: '[disabled]',
91 | 'data-equalTo': '[data-equalTo]',
92 | 'data-notEqualTo': '[data-notEqualTo]',
93 | lessThan: '[lessThan]',
94 | 'data-lessThanEqual': '[data-lessThanEqual]',
95 | errorPlacement: function(error, element) {
96 | if (element.attr('type') == 'radio')
97 | error.insertAfter(element.next().next());
98 | else
99 | error.insertAfter(element);
100 | }
101 | });
102 |
103 | //Apply pattern constraint to input field
104 | var addPatternConstraint = function(element){
105 | var message = 'Must match pattern: /' + $(element).attr('data-pattern') + '/'
106 | if ($(element).is('[flags]'))
107 | message += $(element).attr('flags');
108 | $(element).rules('add', {
109 | pattern: new RegExp($(element).attr('data-pattern'), $(element).attr('flags')),
110 | messages: { pattern: message }
111 | });
112 | }
113 |
114 | // Adds and removes entries when buttons are clicked
115 | $('body').on('click', '.add-entry', function() {
116 | addEntry($(this).parent().children('.template').first())
117 | });
118 | $('body').on('click', '.remove-entry', function() {
119 | removeEntry($(this).parent().children('.template').first())
120 | });
121 |
122 | // Controls different parts of the form showing up depending on whether the user chooses to add a new node or link to an
123 | // existing one.
124 | $('#shacl-form').on('change', ':radio', function(){
125 | // Hide other options
126 | var nodeKindOptions = $(this).siblings('.nodeKindOption');
127 | nodeKindOptions.attr('hidden', 'hidden');
128 | // Disable other input fields
129 | nodeKindOptions.find('input, select').each(function(){
130 | $(this).attr('disabled', 'disabled');
131 | })
132 | // Reveal the selected option
133 | var value = $(this).val()
134 | var selectedOption = $(this).siblings('.nodeKindOption-' + $(this).val())
135 | selectedOption.removeAttr('hidden');
136 | //Enable revealed input fields
137 | selectedOption.find('input, select').each(function(){
138 | if ($(this).parents('.template').length == 0)
139 | $(this).removeAttr('disabled');
140 | })
141 | })
142 |
143 | // Checkboxes that are unchecked aren't submitted with the form
144 | // The solution is for every checkbox to have a hidden partner with prefix 'unchecked:', which will submit if the main
145 | // checkbox is unchecked
146 | // This event ensures that the hidden checkbox is always checked when the main checkbox is unchecked, and the hidden
147 | // checkbox is always unchecked when the main checkbox is checked
148 | $('#shacl-form').on('change', ':checkbox', function(){
149 | if ($(this).is(':checked'))
150 | $('[name="Unchecked ' + $(this).attr('name') + '"]').removeAttr('checked');
151 | else
152 | $('[name="Unchecked ' + $(this).attr('name') + '"]').attr('checked', 'checked');
153 | })
154 |
155 | // Handles everything about adding an entry for a property
156 | var addEntry = function(template, prefill_value, prefill_nodeKind) {
157 | var template_copy = template.clone()
158 | var entries = template.parent().children('.entries');
159 | var max_entries = template_copy.attr('data-max-entries');
160 | var min_entries = template_copy.attr('data-min-entries');
161 | var num_entries = entries.children().length;
162 | var root_id = template.children().find('[name]').attr('name').split(' ').pop();
163 | var id = root_id + "-" + entries.children().length;
164 |
165 | if (max_entries && num_entries >= max_entries) return; // Return if maximum entries is already reached
166 |
167 | // Update the ID through all children of this property
168 | template_copy.find('[name]').each(function(){
169 | $(this).attr('name', $(this).attr('name').replace(root_id, id));
170 | });
171 |
172 | // All entries below or at the minimum number of entries must be required
173 | if (min_entries != undefined && num_entries <= min_entries)
174 | template_copy.children().children().not('[type="checkbox"]').attr('required', 'required');
175 |
176 | // Append our prepared copy of the template to the entries
177 | var last_entry = entries.append(template_copy.html());
178 | num_entries++;
179 |
180 | // Apply prefill value if applicable
181 | if (prefill_value !== undefined && prefill_nodeKind !== undefined) {
182 | last_entry.find(':radio').filter('[name="NodeKind ' + id + '"]').setValue(prefill_nodeKind)
183 | var nodeKindContainer = last_entry.find('.nodeKindOption-' + prefill_nodeKind)
184 | if (nodeKindContainer.length == 0)
185 | last_entry.find('input, select').filter('[name=' + id + ']').first().setValue(prefill_value)
186 | else
187 | nodeKindContainer.find('input, select').filter('[name=' + id + ']').first().setValue(prefill_value)
188 | }
189 |
190 | // Enable input fields. Input fields are disabled when copied from the template
191 | // Apply pattern constraint if it should have one
192 | last_entry.find('input, select').each(function() {
193 | if ($(this).closest('.template').length == 0 && $(this).closest('.nodeKindOption').length == 0) {
194 | $(this).removeAttr('disabled');
195 | if ($(this).is('[data-pattern]'))
196 | addPatternConstraint($(this))
197 | }
198 | });
199 |
200 | // Control Add and Remove buttons
201 | if (num_entries > 0 && (min_entries == undefined || num_entries > min_entries))
202 | template.parent().children('.remove-entry').removeAttr('disabled');
203 | if (max_entries !== undefined && num_entries >= max_entries)
204 | template.parent().children('.add-entry').attr('disabled', 'disabled');
205 | };
206 |
207 | // Handles everything about removing an entry for a property
208 | var removeEntry = function($template){
209 | var template_copy = $template.clone()
210 | var entries = $template.parent().children('.entries');
211 | var min_entries = template_copy.attr('data-min-entries');
212 | var num_entries = entries.children().length;
213 |
214 | // Return if minimum entries is already reached
215 | if ((!min_entries && num_entries == 0) || num_entries <= min_entries) return;
216 | // Removing a property means that the Add button can be enabled again
217 | $template.parent().children('.add-entry').removeAttr('disabled');
218 | // Remove the last entry
219 | entries.children().last().remove();
220 | num_entries--;
221 | // Disable Remove button if we reach the minimum number of entries
222 | if (num_entries <= min_entries || num_entries <= 0)
223 | $template.parent().children('.remove-entry').attr('disabled', 'disabled');
224 | };
225 |
226 | // Adds minimum number of fields when form is loaded
227 | try {
228 | var prefill = JSON.parse($('#shacl-form-prefill').html());
229 | } catch(err) {
230 | var prefill = []
231 | }
232 | $($('.template').get().reverse()).each(function(){
233 | var min_entries = $(this).attr('data-min-entries');
234 | var max_entries = $(this).attr('data-max-entries');
235 | var property_id = $(this).find('[name]').first().attr('name').split(' ').pop();
236 | for (i = 0; i < prefill.length; i++ ) {
237 | if (prefill[i]['id'] == property_id)
238 | var entries = prefill[i]['entries']
239 | }
240 | var num_entries = 0
241 | if (entries == undefined || entries.length < min_entries)
242 | num_entries = min_entries
243 | else if (entries.length > max_entries)
244 | num_entries = max_entries
245 | else
246 | num_entries = entries.length
247 | for (i = 0; i < num_entries; i++) {
248 | if (entries !== undefined && entries.length >= i) {
249 | var prefill_value = entries[i]['value']
250 | var prefill_nodeKind = entries[i]['nodeKind']
251 | }
252 | addEntry($(this), prefill_value, prefill_nodeKind);
253 | }
254 | });
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CSIRO-enviro-informatics/shacl-form/c2b417f21bb97e2ce47adb710851376f1ced3a7c/tests/__init__.py
--------------------------------------------------------------------------------
/tests/expected_results/empty_shape.html:
--------------------------------------------------------------------------------
1 | {% extends "form.html" %}
2 | {% block form_heading %}Create New Person{% endblock %}
3 | {% block form_contents %}
4 |
32 | {% endblock %}
33 | {% block prefill %}
34 |
35 | {% endblock %}
--------------------------------------------------------------------------------
/tests/inputs/empty_file.ttl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CSIRO-enviro-informatics/shacl-form/c2b417f21bb97e2ce47adb710851376f1ced3a7c/tests/inputs/empty_file.ttl
--------------------------------------------------------------------------------
/tests/inputs/empty_shape.ttl:
--------------------------------------------------------------------------------
1 | @prefix dash: .
2 | @prefix rdf: .
3 | @prefix rdfs: .
4 | @prefix schema: .
5 | @prefix sh: .
6 | @prefix xsd: .
7 | @prefix foaf: .
8 | @prefix : .
9 |
10 | :PersonShape1
11 | a sh:NodeShape ;
12 | sh:targetClass schema:Person .
--------------------------------------------------------------------------------
/tests/inputs/implicit_target_class.ttl:
--------------------------------------------------------------------------------
1 | #Borrowed from http://shacl.org/playground/ for testing purposes.
2 |
3 | @prefix dash: .
4 | @prefix rdf: .
5 | @prefix rdfs: .
6 | @prefix schema: .
7 | @prefix sh: .
8 | @prefix xsd: .
9 | @prefix foaf: .
10 | @prefix : .
11 |
12 | schema:Person
13 | a sh:NodeShape, rdfs:Class .
--------------------------------------------------------------------------------
/tests/inputs/inclusive_exclusive.ttl:
--------------------------------------------------------------------------------
1 | #Borrowed from http://shacl.org/playground/ for testing purposes.
2 |
3 | @prefix dash: .
4 | @prefix rdf: .
5 | @prefix rdfs: .
6 | @prefix schema: .
7 | @prefix sh: .
8 | @prefix xsd: .
9 | @prefix foaf: .
10 | @prefix : .
11 |
12 | :PersonShape1
13 | a sh:NodeShape ;
14 | sh:targetClass schema:Person ;
15 | sh:property [
16 | sh:path :gpa ;
17 | sh:minInclusive 1 ;
18 | sh:minExclusive 1 ;
19 | sh:maxInclusive 1 ;
20 | sh:maxExclusive 1 ;
21 | ] .
--------------------------------------------------------------------------------
/tests/inputs/invalid_minCount.ttl:
--------------------------------------------------------------------------------
1 | #Borrowed from http://shacl.org/playground/ for testing purposes.
2 |
3 | @prefix dash: .
4 | @prefix rdf: .
5 | @prefix rdfs: .
6 | @prefix schema: .
7 | @prefix sh: .
8 | @prefix xsd: .
9 | @prefix foaf: .
10 | @prefix : .
11 |
12 | :PersonShape1
13 | a sh:NodeShape ;
14 | sh:targetClass schema:Person ;
15 | sh:property [
16 | sh:path schema:givenName ;
17 | sh:minCount "blah" ;
18 | ] .
--------------------------------------------------------------------------------
/tests/inputs/missing_group.ttl:
--------------------------------------------------------------------------------
1 | #Borrowed from http://shacl.org/playground/ for testing purposes.
2 |
3 | @prefix dash: .
4 | @prefix rdf: .
5 | @prefix rdfs: .
6 | @prefix schema: .
7 | @prefix sh: .
8 | @prefix xsd: .
9 | @prefix foaf: .
10 | @prefix : .
11 |
12 | :PersonShape1
13 | a sh:NodeShape ;
14 | sh:targetClass schema:Person ;
15 | sh:property [
16 | sh:path schema:givenname ;
17 | sh:group :MissingGroup1 ;
18 | ] .
--------------------------------------------------------------------------------
/tests/inputs/no_path.ttl:
--------------------------------------------------------------------------------
1 | #Borrowed from http://shacl.org/playground/ for testing purposes.
2 |
3 | @prefix dash: .
4 | @prefix rdf: .
5 | @prefix rdfs: .
6 | @prefix schema: .
7 | @prefix sh: .
8 | @prefix xsd: .
9 | @prefix foaf: .
10 | @prefix : .
11 |
12 | :PersonShape1
13 | a sh:NodeShape ;
14 | sh:targetClass schema:Person ;
15 | sh:property [
16 | sh:datatype xsd:string ;
17 | ] .
--------------------------------------------------------------------------------
/tests/inputs/no_target_class.ttl:
--------------------------------------------------------------------------------
1 | #Borrowed from http://shacl.org/playground/ for testing purposes.
2 |
3 | @prefix dash: .
4 | @prefix rdf: .
5 | @prefix rdfs: .
6 | @prefix schema: .
7 | @prefix sh: .
8 | @prefix xsd: .
9 | @prefix foaf: .
10 | @prefix : .
11 |
12 | :PersonShape1
13 | a sh:NodeShape .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/blanknode.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty1 ;
9 | sh:nodeKind sh:BlankNode ;
10 | sh:property [
11 | sh:path :testProperty2 ;
12 | ] ;
13 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/blanknode_or_iri.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty1 ;
9 | sh:nodeKind sh:BlankNodeOrIRI ;
10 | sh:property [
11 | sh:path :testProperty2 ;
12 | ] ;
13 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/blanknode_or_iri_hasvalue.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty ;
9 | sh:hasValue "test" ;
10 | sh:nodeKind sh:BlankNodeOrIRI ;
11 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/blanknode_or_iri_without_nested_properties.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty ;
9 | sh:nodeKind sh:BlankNodeOrIRI ;
10 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/blanknode_or_literal.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty1 ;
9 | sh:nodeKind sh:BlankNodeOrLiteral ;
10 | sh:property [
11 | sh:path :testProperty2 ;
12 | ] ;
13 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/blanknode_or_literal_hasvalue.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty ;
9 | sh:hasValue "test" ;
10 | sh:nodeKind sh:BlankNodeOrLiteral ;
11 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/blanknode_or_literal_without_nested_properties.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty ;
9 | sh:nodeKind sh:BlankNodeOrLiteral ;
10 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/blanknode_without_nested_properties.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty ;
9 | sh:nodeKind sh:BlankNode ;
10 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/invalid_nodekind_with_hasvalue_constraint.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty ;
9 | sh:nodeKind sh:Invalid ;
10 | sh:hasValue "test" ;
11 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/invalid_nodekind_with_nested_properties.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty1 ;
9 | sh:nodeKind sh:Invalid ;
10 | sh:property [
11 | sh:path :testProperty2 ;
12 | ] ;
13 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/invalid_nodekind_without_nested_properties.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:nodeKind sh:Invalid ;
9 | sh:path :testProperty ;
10 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/iri.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty ;
9 | sh:nodeKind sh:IRI ;
10 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/iri_or_literal.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty ;
9 | sh:nodeKind sh:IRIOrLiteral ;
10 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/iri_or_literal_hasvalue.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty ;
9 | sh:hasValue "test" ;
10 | sh:nodeKind sh:IRIOrLiteral ;
11 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/iri_or_literal_with_nested_properties.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty1 ;
9 | sh:nodeKind sh:IRIOrLiteral ;
10 | sh:property [
11 | sh:path :testProperty2 ;
12 | ] ;
13 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/iri_with_nested_properties.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty1 ;
9 | sh:nodeKind sh:IRI ;
10 | sh:property [
11 | sh:path :testProperty2 ;
12 | ] ;
13 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/literal.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty ;
9 | sh:nodeKind sh:Literal ;
10 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/literal_with_nested_properties.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty1 ;
9 | sh:nodeKind sh:Literal ;
10 | sh:property [
11 | sh:path :testProperty2 ;
12 | ] ;
13 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/missing_nodekind_with_hasvalue_constraint.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty ;
9 | sh:hasValue "test" ;
10 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/missing_nodekind_with_nested_properties.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty1 ;
9 | sh:property [
10 | sh:path :testProperty2 ;
11 | ] ;
12 | ] .
--------------------------------------------------------------------------------
/tests/inputs/node_kind/missing_nodekind_without_nested_properties.ttl:
--------------------------------------------------------------------------------
1 | @prefix sh: .
2 | @prefix : .
3 |
4 | :TestShape
5 | a sh:NodeShape ;
6 | sh:targetClass :testClass ;
7 | sh:property [
8 | sh:path :testProperty ;
9 | ] .
--------------------------------------------------------------------------------
/tests/inputs/recursion.ttl:
--------------------------------------------------------------------------------
1 | @prefix rdf: .
2 | @prefix rdfs: .
3 | @prefix schema: .
4 | @prefix sh: .
5 | @prefix xsd: .
6 | @prefix foaf: .
7 | @prefix : .
8 |
9 | :PersonShape2
10 | a sh:NodeShape ;
11 | sh:targetClass schema:Person ;
12 | sh:property [
13 | sh:path schema:givenName ;
14 | sh:name "Given Name" ;
15 | sh:minCount 1 ;
16 | sh:maxCount 1 ;
17 | sh:order 1 ;
18 | ] ;
19 | sh:property [
20 | sh:path :hasParent ;
21 | sh:name "Parents" ;
22 | sh:minCount 2 ;
23 | sh:maxCount 2 ;
24 | sh:node :PersonShape2 ;
25 | ] .
--------------------------------------------------------------------------------
/tests/inputs/test_shape.ttl:
--------------------------------------------------------------------------------
1 | @prefix dash: .
2 | @prefix rdf: .
3 | @prefix rdfs: .
4 | @prefix schema: .
5 | @prefix sh: .
6 | @prefix xsd: .
7 | @prefix foaf: .
8 | @prefix : .
9 |
10 | :PersonShape1
11 | a sh:NodeShape ;
12 | sh:targetClass schema:Person ;
13 | sh:property [
14 | sh:path schema:givenName ;
15 | sh:datatype xsd:string ;
16 | sh:description "The first name of a person." ;
17 | sh:defaultValue "Steve" ;
18 | sh:name "Given name" ;
19 | sh:order 1 ;
20 | sh:in ( "Steve" "Terrence" ) ;
21 | sh:equals schema:familyName ;
22 | ] ;
23 | sh:property [
24 | sh:path schema:familyName ;
25 | sh:datatype xsd:string ;
26 | sh:pattern "^G" ;
27 | sh:flags "i" ;
28 | sh:languageIn ("en" "es") ;
29 | ] ;
30 | sh:property [
31 | sh:path schema:birthDate ;
32 | sh:lessThan schema:deathDate ;
33 | sh:maxCount 1 ;
34 | sh:minCount 1 ;
35 | sh:group :DateGroup1 ;
36 | ] ;
37 | sh:node :AddressShape1 ;
38 | sh:property [
39 | sh:path :gpa ;
40 | sh:minInclusive 1 ;
41 | sh:maxInclusive 7 ;
42 | sh:datatype xsd:integer ;
43 | sh:lessThanOrEquals :goalGpa ;
44 | ] ;
45 | sh:property [
46 | sh:path :goalGpa ;
47 | sh:datatype xsd:integer ;
48 | sh:minExclusive 0 ;
49 | sh:maxExclusive 8 ;
50 | ] ;
51 | sh:property [
52 | sh:path :likesCats ;
53 | sh:disjoint :likesDogs ;
54 | ] ;
55 | sh:property [
56 | sh:node :LikesDogsShape ;
57 | ] ;
58 | sh:node :LikesBirdsShape .
59 |
60 | :DateGroup1
61 | a sh:PropertyGroup ;
62 | sh:order 0 ;
63 | rdfs:label "Birth & Death Date" .
64 |
65 | :LikesDogsShape
66 | a sh:NodeShape ;
67 | sh:path :likesDogs .
68 |
69 | :LikesBirdsShape
70 | a sh:NodeShape ;
71 | sh:property [
72 | sh:path :likesBirds ;
73 | ] .
74 |
75 | :AddressShape1
76 | a sh:NodeShape ;
77 | sh:node :AddressShape2 .
78 |
79 | :AddressShape2
80 | a sh:NodeShape ;
81 | sh:node :AddressCountryShape ;
82 | sh:property [
83 | sh:path schema:address ;
84 | sh:property [
85 | sh:node :StreetAddressShape ;
86 | ] ;
87 | sh:property [
88 | sh:path schema:postalCode ;
89 | sh:order 2 ;
90 | ] ;
91 | ] .
92 |
93 | :StreetAddressShape
94 | a sh:NodeShape ;
95 | sh:path schema:streetAddress ;
96 | sh:order 1 .
97 |
98 | :AddressCountryShape
99 | a sh:NodeShape ;
100 | sh:property [
101 | sh:path schema:addressCountry ;
102 | sh:order 3 ;
103 | ] .
--------------------------------------------------------------------------------
/tests/test_main.py:
--------------------------------------------------------------------------------
1 | import os
2 | import pytest
3 | import filecmp
4 | import copy
5 | import shutil
6 | from generate_form import generate_form, sort_composite_property, assign_id, check_property, find_paired_properties
7 |
8 |
9 | def test_no_filename():
10 | with pytest.raises(Exception):
11 | generate_form(None, None)
12 |
13 |
14 | def test_file_exists():
15 | with pytest.raises(Exception):
16 | generate_form('test', None)
17 |
18 |
19 | def test_empty_file():
20 | with pytest.raises(Exception):
21 | with open('inputs/empty_file.ttl') as f:
22 | generate_form(f, form_destination='result.html', map_destination='result.ttl')
23 |
24 |
25 | def test_empty_shape():
26 | with open('inputs/empty_shape.ttl') as f:
27 | generate_form(f, form_destination='result.html', map_destination='result.ttl')
28 | assert os.path.exists('result.html')
29 | assert filecmp.cmp('result.html', 'expected_results/empty_shape.html')
30 |
31 |
32 | def test_sort_composite_property_single():
33 | # This function changes the structure of its input, make a copy to see whether it changed
34 | prop = {'path': 'http://xmlns.com/foaf/0.1/phone', 'name': 'Phone Number', 'order': None}
35 | result = copy.deepcopy(prop)
36 | sort_composite_property(result)
37 | assert result == prop
38 |
39 |
40 | def test_sort_composite_property_order():
41 | # This function changes the structure of its input, make a copy to see whether it changed
42 | # Should order the two properties by their 'order' key
43 | prop = {'property': [{'order': 2, 'path': 'http://schema.org/streetAddress'},
44 | {'order': 1, 'path': 'http://schema.org/postalCode'}],
45 | 'path': 'http://schema.org/address',
46 | 'name': 'Address',
47 | 'order': None}
48 | result = {'property': [{'order': 1, 'path': 'http://schema.org/postalCode'},
49 | {'order': 2, 'path': 'http://schema.org/streetAddress'}],
50 | 'path': 'http://schema.org/address',
51 | 'name': 'Address',
52 | 'order': None}
53 | sort_composite_property(prop)
54 | assert prop == result
55 |
56 |
57 | def test_assign_id_no_parent_id():
58 | prop = dict()
59 | expected_result = {'id': 0}
60 | assign_id(prop, 0)
61 | assert prop == expected_result
62 |
63 |
64 | def test_assign_id_parent_id():
65 | prop = dict()
66 | expected_result = {'id': '1:0'}
67 | assign_id(prop, 0, '1')
68 | assert prop == expected_result
69 |
70 |
71 | def test_assign_id_nested_property():
72 | prop = {'property': [{}, {}]}
73 | expected_result = {'property': [{'id': '0:0'}, {'id': '0:1'}], 'id': 0}
74 | assign_id(prop, 0)
75 | assert prop == expected_result
76 |
77 |
78 | def test_check_property_match():
79 | prop = {'path': 'http://schema.org/givenName', 'id': 0}
80 | path = 'http://schema.org/givenName'
81 | result = check_property(prop, path)
82 | expected_result = 0
83 | assert result == expected_result
84 |
85 |
86 | def test_check_property_no_match():
87 | prop = {'path': 'http://schema.org/familyName', 'id': 0}
88 | path = 'http://schema.org/givenName'
89 | result = check_property(prop, path)
90 | expected_result = None
91 | assert result == expected_result
92 |
93 |
94 | def test_check_property_nested_property_match():
95 | prop = {'path': 'http://schema.org/familyName', 'property': [{'path': 'http://schema.org/givenName', 'id': 0}]}
96 | path = 'http://schema.org/givenName'
97 | result = check_property(prop, path)
98 | expected_result = 0
99 | assert result == expected_result
100 |
101 |
102 | def test_check_property_nested_property_no_match():
103 | prop = {'path': 'http://schema.org/familyName', 'property': [{'path': 'http://schema.org/familyName', 'id': 0}]}
104 | path = 'http://schema.org/givenName'
105 | result = check_property(prop, path)
106 | expected_result = None
107 | assert result == expected_result
108 |
109 |
110 | def test_find_paired_properties_ungrouped():
111 | shape = {'groups': [], 'properties': [{'path': 'A', 'equals': 'B', 'id': 0, 'property': [{'path': 'B', 'id': 1}]}]}
112 | prop = {'path': 'A', 'equals': 'B', 'id': 0, 'property': [{'path': 'B', 'id': 1}]}
113 | constraint = 'equals'
114 | expected_result = {'path': 'A', 'equals': 1, 'id': 0, 'property': [{'path': 'B', 'id': 1}]}
115 | find_paired_properties(shape, prop, constraint)
116 | assert prop == expected_result
117 |
118 |
119 | def test_find_paired_properties_grouped():
120 | shape = {'groups': [{'properties': [{'path': 'A', 'equals': 'B', 'id': 0, 'property': [{'path': 'B', 'id': 1}]}]}],
121 | 'properties': []}
122 | prop = {'path': 'A', 'equals': 'B', 'id': 0, 'property': [{'path': 'B', 'id': 1}]}
123 | constraint = 'equals'
124 | expected_result = {'path': 'A', 'equals': 1, 'id': 0, 'property': [{'path': 'B', 'id': 1}]}
125 | find_paired_properties(shape, prop, constraint)
126 | assert prop == expected_result
127 |
128 |
129 | def test_find_paired_properties_nested():
130 | shape = {'groups': [], 'properties': [{'path': 'A', 'id': 0, 'property': [{'path': 'B', 'equals': 'A', 'id': 1}]}]}
131 | prop = {'path': 'A', 'id': 0, 'property': [{'path': 'B', 'equals': 'A', 'id': 1}]}
132 | constraint = 'property'
133 | expected_result = {'path': 'A', 'id': 0, 'property': [{'path': 'B', 'equals': 0, 'id': 1}]}
134 | find_paired_properties(shape, prop, constraint)
135 | assert prop == expected_result
136 |
137 |
138 | def test_shape():
139 | # Contents of result can't be verified due to RDF and therefore the HTML result being unordered
140 | if os.path.exists('results'):
141 | shutil.rmtree('results')
142 | with open('inputs/test_shape.ttl') as f:
143 | generate_form(f, form_destination='result.html', map_destination='result.ttl')
144 | assert os.path.exists('result.html')
145 |
--------------------------------------------------------------------------------
/tests/test_rdfhandling.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from rdflib.term import URIRef, Literal
3 | from rdfhandling import RDFHandler, SHACL
4 |
5 |
6 | def test_empty_file():
7 | # Checks behaviour when an empty file is supplied
8 | with open('inputs/empty_file.ttl') as f:
9 | rdf_handler = RDFHandler(f)
10 | assert rdf_handler.get_shape() is None
11 |
12 |
13 | def test_no_target_class():
14 | # Checks behavior when the shape provided doesn't have a target class
15 | with open('inputs/no_target_class.ttl') as f:
16 | rdf_handler = RDFHandler(f)
17 | with pytest.raises(Exception):
18 | rdf_handler.get_shape()
19 |
20 |
21 | def test_empty_shape():
22 | # Valid but empty shape
23 | expected_result = dict()
24 | expected_result['target_class'] = URIRef('http://schema.org/Person')
25 | expected_result['groups'] = list()
26 | expected_result['properties'] = list()
27 | expected_result['closed'] = False
28 | with open('inputs/empty_shape.ttl') as f:
29 | rdf_handler = RDFHandler(f)
30 | result = rdf_handler.get_shape()
31 | assert result == expected_result
32 |
33 |
34 | def test_no_path():
35 | # Checks behaviour when a property doesn't have a compulsory path constraint
36 | with open('inputs/no_path.ttl') as f:
37 | rdf_handler = RDFHandler(f)
38 | with pytest.raises(Exception):
39 | rdf_handler.get_shape()
40 |
41 |
42 | def test_recursion():
43 | # Checks to make sure recursion isn't accepted
44 | with open('inputs/recursion.ttl') as f:
45 | rdf_handler = RDFHandler(f)
46 | with pytest.raises(Exception):
47 | rdf_handler.get_shape()
48 |
49 |
50 | def test_implicit_target_class():
51 | # Checks to make sure the target class is correctly identified when implicitly declared
52 | with open('inputs/implicit_target_class.ttl') as f:
53 | rdf_handler = RDFHandler(f)
54 | shape = rdf_handler.get_shape()
55 | assert str(shape['target_class']) == 'http://schema.org/Person'
56 |
57 |
58 | def test_missing_group():
59 | # Checks to make sure an exception is thrown if a group is referenced but does not exist
60 | with open('inputs/missing_group.ttl') as f:
61 | rdf_handler = RDFHandler(f)
62 | with pytest.raises(Exception):
63 | rdf_handler.get_shape()
64 |
65 |
66 | def test_path():
67 | # Check the path is read
68 | expected_path = 'http://schema.org/givenName'
69 | with open('inputs/test_shape.ttl') as f:
70 | rdf_handler = RDFHandler(f)
71 | properties = rdf_handler.get_shape()['properties']
72 | assert any(str(p['path'] == expected_path for p in properties))
73 |
74 |
75 | def test_invalid_mincount():
76 | # Check that a non-integer minCount raises the appropriate error
77 | with open('inputs/invalid_minCount.ttl') as f:
78 | rdf_handler = RDFHandler(f)
79 | with pytest.raises(Exception):
80 | rdf_handler.get_shape()
81 |
82 |
83 | def test_node_kind_blanknode():
84 | # Check no warnings are raised when there are nested properties
85 | with pytest.warns(None) as record:
86 | with open('inputs/node_kind/blanknode.ttl') as f:
87 | shape = RDFHandler(f).get_shape()
88 | for r in record.list:
89 | print(r)
90 | assert not record.list
91 |
92 | # Check the sh:nodeKind constraint was read correctly
93 | node_kind = None
94 | for p in shape['properties']:
95 | if str(p['path']) == 'http://example.org/ex#testProperty1':
96 | node_kind = p['nodeKind']
97 | assert node_kind == SHACL + 'BlankNode'
98 |
99 |
100 | def test_node_kind_blanknode_without_nested_properties():
101 | # Check a warning is raised when there are no nested properties
102 | with pytest.warns(UserWarning) as record:
103 | with open('inputs/node_kind/blanknode_without_nested_properties.ttl') as f:
104 | shape = RDFHandler(f).get_shape()
105 |
106 | # Check that the correct warning is raised
107 | assert record[0].message.args[0] == 'Property "testProperty" has constraint "sh:nodeKind" with value ' \
108 | '"sh:BlankNode" but no property shapes are provided. This property will have ' \
109 | 'no input fields.'
110 |
111 | # Check the sh:nodeKind constraint was read correctly
112 | node_kind = None
113 | for p in shape['properties']:
114 | if str(p['path']) == 'http://example.org/ex#testProperty':
115 | node_kind = p['nodeKind']
116 | assert node_kind == SHACL + 'BlankNode'
117 |
118 |
119 | def test_node_kind_iri():
120 | # Check no warnings are raised when there are no nested properties
121 | with pytest.warns(None) as record:
122 | with open('inputs/node_kind/iri.ttl') as f:
123 | shape = RDFHandler(f).get_shape()
124 | assert not record.list
125 |
126 | # Check the sh:nodeKind constraint was read correctly
127 | node_kind = None
128 | for p in shape['properties']:
129 | if str(p['path']) == 'http://example.org/ex#testProperty':
130 | node_kind = p['nodeKind']
131 | assert node_kind == SHACL + 'IRI'
132 |
133 |
134 | def test_node_kind_iri_with_nested_properties():
135 | # Check a warning is raised when there are nested properties
136 | with pytest.warns(UserWarning) as record:
137 | with open('inputs/node_kind/iri_with_nested_properties.ttl') as f:
138 | shape = RDFHandler(f).get_shape()
139 |
140 | # Check that the correct warning is raised
141 | assert record[0].message.args[0] == 'Property "testProperty1" has constraint "sh:nodeKind" with value ' \
142 | '"http://www.w3.org/ns/shacl#IRI". The property shapes provided in this ' \
143 | 'property will be ignored.'
144 |
145 | # Check the sh:nodeKind constraint was read correctly
146 | node_kind = None
147 | for p in shape['properties']:
148 | if str(p['path']) == 'http://example.org/ex#testProperty1':
149 | node_kind = p['nodeKind']
150 | assert node_kind == SHACL + 'IRI'
151 |
152 |
153 | def test_node_kind_literal():
154 | # Check no warnings are raised when there are no nested properties
155 | with pytest.warns(None) as record:
156 | with open('inputs/node_kind/literal.ttl') as f:
157 | shape = RDFHandler(f).get_shape()
158 | assert not record.list
159 |
160 | # Check the sh:nodeKind constraint was read correctly
161 | node_kind = None
162 | for p in shape['properties']:
163 | if str(p['path']) == 'http://example.org/ex#testProperty':
164 | node_kind = p['nodeKind']
165 | assert node_kind == SHACL + 'Literal'
166 |
167 |
168 | def test_node_kind_literal_with_nested_properties():
169 | # Check a warning is raised when there are nested properties
170 | with pytest.warns(UserWarning) as record:
171 | with open('inputs/node_kind/literal_with_nested_properties.ttl') as f:
172 | shape = RDFHandler(f).get_shape()
173 |
174 | # Check that the correct warning is raised
175 | assert record[0].message.args[0] == 'Property "testProperty1" has constraint "sh:nodeKind" with value ' \
176 | '"http://www.w3.org/ns/shacl#Literal". The property shapes provided in this ' \
177 | 'property will be ignored.'
178 |
179 | # Check the sh:nodeKind constraint was read correctly
180 | node_kind = None
181 | for p in shape['properties']:
182 | if str(p['path']) == 'http://example.org/ex#testProperty1':
183 | node_kind = p['nodeKind']
184 | assert node_kind == SHACL + 'Literal'
185 |
186 |
187 | def test_node_kind_blanknode_or_iri():
188 | # Check no warnings are raised when there are nested properties
189 | with pytest.warns(None) as record:
190 | with open('inputs/node_kind/blanknode_or_iri.ttl') as f:
191 | shape = RDFHandler(f).get_shape()
192 | assert not record.list
193 |
194 | # Check the sh:nodeKind constraint was read correctly
195 | node_kind = None
196 | for p in shape['properties']:
197 | if str(p['path']) == 'http://example.org/ex#testProperty1':
198 | node_kind = p['nodeKind']
199 | assert node_kind == SHACL + 'BlankNodeOrIRI'
200 |
201 |
202 | def test_node_kind_blanknode_or_iri_without_nested_properties():
203 | # Check a warning is raised when there are no nested properties
204 | with pytest.warns(UserWarning) as record:
205 | with open('inputs/node_kind/blanknode_or_iri_without_nested_properties.ttl') as f:
206 | shape = RDFHandler(f).get_shape()
207 |
208 | # Check that the correct warning is raised
209 | assert record[0].message.args[0] == 'Property "testProperty" has constraint "sh:nodeKind" with value ' \
210 | '"http://www.w3.org/ns/shacl#BlankNodeOrIRI" but no property shapes are ' \
211 | 'provided. If the user selects the "blank node" option, this property will ' \
212 | 'have no input fields.'
213 |
214 | # Check the sh:nodeKind constraint was read correctly
215 | node_kind = None
216 | for p in shape['properties']:
217 | if str(p['path']) == 'http://example.org/ex#testProperty':
218 | node_kind = p['nodeKind']
219 | assert node_kind == SHACL + 'BlankNodeOrIRI'
220 |
221 |
222 | def test_node_kind_blanknode_or_literal():
223 | # Check no warnings are raised when there are nested properties
224 | with pytest.warns(None) as record:
225 | with open('inputs/node_kind/blanknode_or_literal.ttl') as f:
226 | shape = RDFHandler(f).get_shape()
227 | assert not record.list
228 |
229 | # Check the sh:nodeKind constraint was read correctly
230 | node_kind = None
231 | for p in shape['properties']:
232 | if str(p['path']) == 'http://example.org/ex#testProperty1':
233 | node_kind = p['nodeKind']
234 | assert node_kind == SHACL + 'BlankNodeOrLiteral'
235 |
236 |
237 | def test_node_kind_blanknode_or_literal_without_nested_properties():
238 | # Check a warning is raised when there are no nested properties
239 | with pytest.warns(UserWarning) as record:
240 | with open('inputs/node_kind/blanknode_or_literal_without_nested_properties.ttl') as f:
241 | shape = RDFHandler(f).get_shape()
242 |
243 | # Check that the correct warning is raised
244 | assert record[0].message.args[0] == 'Property "testProperty" has constraint "sh:nodeKind" with value ' \
245 | '"http://www.w3.org/ns/shacl#BlankNodeOrLiteral" but no property shapes are ' \
246 | 'provided. If the user selects the "blank node" option, this property will ' \
247 | 'have no input fields.'
248 |
249 | # Check the sh:nodeKind constraint was read correctly
250 | node_kind = None
251 | for p in shape['properties']:
252 | if str(p['path']) == 'http://example.org/ex#testProperty':
253 | node_kind = p['nodeKind']
254 | assert node_kind == SHACL + 'BlankNodeOrLiteral'
255 |
256 |
257 | def test_node_kind_iri_or_literal():
258 | # Check no warnings are raised when there are no nested properties
259 | with pytest.warns(None) as record:
260 | with open('inputs/node_kind/iri_or_literal.ttl') as f:
261 | shape = RDFHandler(f).get_shape()
262 | assert not record.list
263 |
264 | # Check the sh:nodeKind constraint was read correctly
265 | node_kind = None
266 | for p in shape['properties']:
267 | if str(p['path']) == 'http://example.org/ex#testProperty':
268 | node_kind = p['nodeKind']
269 | assert node_kind == SHACL + 'IRIOrLiteral'
270 |
271 |
272 | def test_node_kind_iri_or_literal_with_nested_properties():
273 | # Check a warning is raised when there are nested properties
274 | with pytest.warns(UserWarning) as record:
275 | with open('inputs/node_kind/iri_or_literal_with_nested_properties.ttl') as f:
276 | shape = RDFHandler(f).get_shape()
277 |
278 | # Check that the correct warning is raised
279 | assert record[0].message.args[0] == 'Property "testProperty1" has constraint "sh:nodeKind" with value ' \
280 | '"http://www.w3.org/ns/shacl#IRIOrLiteral". The property shapes provided in ' \
281 | 'this property will be ignored.'
282 |
283 | # Check the sh:nodeKind constraint was read correctly
284 | node_kind = None
285 | for p in shape['properties']:
286 | if str(p['path']) == 'http://example.org/ex#testProperty1':
287 | node_kind = p['nodeKind']
288 | assert node_kind == SHACL + 'IRIOrLiteral'
289 |
290 |
291 | def test_node_kind_missing_with_hasvalue_constraint():
292 | # Check that a property with a missing sh:nodeKind constraint is automatically assigned a value of sh:Literal when
293 | # the sh:hasValue constraint is present
294 | with open('inputs/node_kind/missing_nodekind_with_hasvalue_constraint.ttl') as f:
295 | shape = RDFHandler(f).get_shape()
296 | node_kind = None
297 | for p in shape['properties']:
298 | if str(p['path']) == 'http://example.org/ex#testProperty':
299 | node_kind = p['nodeKind']
300 | assert node_kind == SHACL + 'Literal'
301 |
302 |
303 | def test_node_kind_missing_without_nested_properties():
304 | # Check that a property without nested properties is automatically assigned a value of sh:IRIOrLiteral when
305 | # sh:nodeKind isn't provided
306 | with open('inputs/node_kind/missing_nodekind_without_nested_properties.ttl') as f:
307 | shape = RDFHandler(f).get_shape()
308 | node_kind = None
309 | for p in shape['properties']:
310 | if str(p['path']) == 'http://example.org/ex#testProperty':
311 | node_kind = p['nodeKind']
312 | assert node_kind == SHACL + 'IRIOrLiteral'
313 |
314 |
315 | def test_node_kind_missing_with_nested_properties():
316 | # Check that a property with nested properties is automatically assigned a value of sh:BlankNodeOrIRI when
317 | # sh:nodeKind isn't provided
318 | with open('inputs/node_kind/missing_nodekind_with_nested_properties.ttl') as f:
319 | shape = RDFHandler(f).get_shape()
320 | node_kind = None
321 | for p in shape['properties']:
322 | if str(p['path']) == 'http://example.org/ex#testProperty1':
323 | node_kind = p['nodeKind']
324 | assert node_kind == SHACL + 'BlankNodeOrIRI'
325 |
326 |
327 | def test_node_kind_invalid_without_nested_properties():
328 | # Check that a property without nested properties is automatically assigned a value of sh:IRIOrLiteral when
329 | # sh:nodeKind isn't a permitted value
330 | with pytest.warns(UserWarning) as record:
331 | with open('inputs/node_kind/invalid_nodekind_without_nested_properties.ttl') as f:
332 | shape = RDFHandler(f).get_shape()
333 | node_kind = None
334 | for p in shape['properties']:
335 | if str(p['path']) == 'http://example.org/ex#testProperty':
336 | node_kind = p['nodeKind']
337 | assert node_kind == SHACL + 'IRIOrLiteral'
338 |
339 | # Check that a warning is raised
340 | assert record[0].message.args[0] == 'Property "testProperty" has constraint "sh:nodeKind" with invalid value ' \
341 | '"http://www.w3.org/ns/shacl#Invalid". Replacing with ' \
342 | '"http://www.w3.org/ns/shacl#IRIOrLiteral".'
343 |
344 |
345 | def test_node_kind_invalid_with_nested_properties():
346 | # Check that a property with nested properties is automatically assigned a value of sh:BlankNodeOrIRI when
347 | # sh:nodeKind isn't a permitted value
348 | with pytest.warns(UserWarning) as record:
349 | with open('inputs/node_kind/invalid_nodekind_with_nested_properties.ttl') as f:
350 | shape = RDFHandler(f).get_shape()
351 | node_kind = None
352 | for p in shape['properties']:
353 | if str(p['path']) == 'http://example.org/ex#testProperty1':
354 | node_kind = p['nodeKind']
355 | assert node_kind == SHACL + 'BlankNodeOrIRI'
356 |
357 | # Check that a warning is raised
358 | assert record[0].message.args[0] == 'Property "testProperty1" has constraint "sh:nodeKind" with invalid value ' \
359 | '"http://www.w3.org/ns/shacl#Invalid". Replacing with ' \
360 | '"http://www.w3.org/ns/shacl#BlankNodeOrIRI".'
361 |
362 |
363 | def test_node_kind_invalid_with_hasvalue_constraint():
364 | # Check that a property with an invalid sh:nodeKind is automatically assigned a value of sh:Literal when the
365 | # sh:hasValue constraint is present
366 | with pytest.warns(UserWarning) as record:
367 | with open('inputs/node_kind/invalid_nodekind_with_hasvalue_constraint.ttl') as f:
368 | shape = RDFHandler(f).get_shape()
369 | node_kind = None
370 | for p in shape['properties']:
371 | if str(p['path']) == 'http://example.org/ex#testProperty':
372 | node_kind = p['nodeKind']
373 | assert node_kind == SHACL + 'Literal'
374 |
375 | # Check that a warning is raised
376 | assert record[0].message.args[0] == 'Property "testProperty" has constraint "sh:nodeKind" with invalid value ' \
377 | '"http://www.w3.org/ns/shacl#Invalid". Replacing with ' \
378 | '"http://www.w3.org/ns/shacl#Literal".'
379 |
380 |
381 | def test_node_blanknode_or_iri_hasvalue():
382 | # Check that a property with sh:nodeKind sh:BlankNodeOrIRI is changed to sh:IRI when the sh:hasValue constraint is
383 | # present
384 | with pytest.warns(UserWarning) as record:
385 | with open('inputs/node_kind/blanknode_or_iri_hasvalue.ttl') as f:
386 | shape = RDFHandler(f).get_shape()
387 | node_kind = None
388 | for p in shape['properties']:
389 | if str(p['path']) == 'http://example.org/ex#testProperty':
390 | node_kind = p['nodeKind']
391 | assert node_kind == SHACL + 'IRI'
392 |
393 | # Check that a warning is raised
394 | assert record[0].message.args[0] == 'Property "testProperty" has constraint "sh:nodeKind" with value ' \
395 | '"http://www.w3.org/ns/shacl#BlankNodeOrIRI" which is incompatible with ' \
396 | 'constraint sh:hasValue. Replacing with "http://www.w3.org/ns/shacl#IRI".'
397 |
398 |
399 | def test_node_iri_or_literal_has_value():
400 | # Check that a property with sh:nodeKind sh:IRIOrLiteral is changed to sh:Literal when the sh:hasValue constraint
401 | # is present
402 | with pytest.warns(UserWarning) as record:
403 | with open('inputs/node_kind/iri_or_literal_hasvalue.ttl') as f:
404 | shape = RDFHandler(f).get_shape()
405 | node_kind = None
406 | for p in shape['properties']:
407 | if str(p['path']) == 'http://example.org/ex#testProperty':
408 | node_kind = p['nodeKind']
409 | assert node_kind == SHACL + 'Literal'
410 |
411 | # Check that a warning is raised
412 | assert record[0].message.args[0] == 'Property "testProperty" has constraint "sh:nodeKind" with value ' \
413 | '"http://www.w3.org/ns/shacl#IRIOrLiteral" which is incompatible with ' \
414 | 'constraint sh:hasValue. Replacing with "http://www.w3.org/ns/shacl#Literal".'
415 |
416 |
417 | def test_node_blanknode_or_literal_has_value():
418 | # Check that a property with sh:nodeKind sh:BlankNodeOrLiteral is changed to sh:Literal when the sh:hasValue
419 | # constraint is present
420 | with pytest.warns(UserWarning) as record:
421 | with open('inputs/node_kind/blanknode_or_literal_hasvalue.ttl') as f:
422 | shape = RDFHandler(f).get_shape()
423 | node_kind = None
424 | for p in shape['properties']:
425 | if str(p['path']) == 'http://example.org/ex#testProperty':
426 | node_kind = p['nodeKind']
427 | assert node_kind == SHACL + 'Literal'
428 |
429 | # Check that a warning is raised
430 | assert record[0].message.args[0] == 'Property "testProperty" has constraint "sh:nodeKind" with value ' \
431 | '"http://www.w3.org/ns/shacl#BlankNodeOrLiteral" which is incompatible with ' \
432 | 'constraint sh:hasValue. Replacing with "http://www.w3.org/ns/shacl#Literal".'
433 |
434 |
435 | def test_shape():
436 | shape = RDFHandler(open('inputs/test_shape.ttl')).get_shape()
437 | # Run the following tests on the test shape to avoid getting it every time
438 | # They won't be automatically discovered by pytest without the test_ prefix
439 | constraint_generic_test(shape)
440 | constraint_name_test(shape)
441 | constraint_order_test(shape)
442 | constraint_mincount_test(shape)
443 | constraint_in_test(shape)
444 | constraint_languagein_test(shape)
445 | constraint_min_test(shape)
446 | constraint_max_test(shape)
447 | nested_properties_test(shape)
448 | node_test(shape)
449 | group_test(shape)
450 |
451 |
452 | def constraint_generic_test(shape):
453 | # Check the desc is read
454 | expected_desc = 'The first name of a person.'
455 | for p in shape['properties']:
456 | if p['path'] == 'http://schema.org/givenName':
457 | assert str(p['description']) == expected_desc
458 |
459 |
460 | def constraint_name_test(shape):
461 | # Check the name is read
462 | expected_name = 'Given name'
463 | properties = shape['properties']
464 | for p in properties:
465 | if p['path'] == 'http://schema.org/givenName':
466 | assert str(p['name']) == expected_name
467 |
468 | # Check name derived from URI
469 | expected_name = 'birthDate'
470 | groups = shape['groups']
471 | for g in groups:
472 | properties.extend(g['properties'])
473 | for p in properties:
474 | if p['path'] == 'http://schema.org/birthDate':
475 | assert str(p['name']) == expected_name
476 |
477 |
478 | def constraint_order_test(shape):
479 | # Check the order is read
480 | expected_value = 1
481 | properties = shape['properties']
482 | for p in properties:
483 | if p['path'] == 'http://schema.org/givenName':
484 | assert int(p['order']) == expected_value
485 |
486 | # Check the order is correctly set to None when it isn't given
487 | for p in properties:
488 | if p['path'] == 'http://schema.org/familyName':
489 | assert p['order'] is None
490 |
491 |
492 | def constraint_mincount_test(shape):
493 | # Check the minimum count is read
494 | expected_value = 1
495 | for p in shape['properties']:
496 | if p['path'] == 'http://schema.org/birthDate':
497 | assert int(p['minCount']) == expected_value
498 |
499 |
500 | def constraint_in_test(shape):
501 | # Check that the 'in' constraint options are read
502 | expected_value = ['Steve', 'Terrence']
503 | for p in shape['properties']:
504 | if p['path'] == 'http://schema.org/givenName':
505 | assert p['in'] == expected_value
506 |
507 |
508 | def constraint_languagein_test(shape):
509 | # Check that the 'languageIn' constraint options are read
510 | expected_value = ['en', 'es']
511 | for p in shape['properties']:
512 | if p['path'] == 'http://schema.org/familyName':
513 | assert p['languageIn'] == expected_value
514 |
515 |
516 | def constraint_min_test(shape):
517 | # Check that the min is read
518 | expected_value = 1
519 | for p in shape['properties']:
520 | if p['path'] == 'http://example.org/ex#gpa':
521 | assert p['min'] == expected_value
522 |
523 | # Check that the minimum is correct when calculated from the minExclusive constraint
524 | expected_value = 1
525 | for p in shape['properties']:
526 | if p['path'] == 'http://example.org/ex#goalGpa':
527 | assert p['min'] == expected_value
528 |
529 |
530 | def constraint_max_test(shape):
531 | # Check that the min is read
532 | expected_value = 7
533 | for p in shape['properties']:
534 | if p['path'] == 'http://example.org/ex#gpa':
535 | assert p['max'] == expected_value
536 |
537 | # Check that the maximum is correct when calculated from the maxExclusive constraint
538 | expected_value = 7
539 | for p in shape['properties']:
540 | if p['path'] == 'http://example.org/ex#goalGpa':
541 | assert p['max'] == expected_value
542 |
543 |
544 | def nested_properties_test(shape):
545 | # Check that properties within properties are correctly read
546 | expected_value = [{
547 | 'node': 'http://example.org/ex#StreetAddressShape',
548 | 'order': '1', 'path': 'http://schema.org/streetAddress',
549 | 'type': 'http://www.w3.org/ns/shacl#NodeShape',
550 | 'name': 'streetAddress',
551 | 'nodeKind': 'http://www.w3.org/ns/shacl#IRIOrLiteral'
552 | }, {
553 | 'order': '2',
554 | 'path': 'http://schema.org/postalCode',
555 | 'name': 'postalCode',
556 | 'nodeKind': 'http://www.w3.org/ns/shacl#IRIOrLiteral'
557 | }]
558 |
559 | prop = None
560 | for p in shape['properties']:
561 | if p['path'] == 'http://schema.org/address':
562 | p['property'].sort(key=lambda x: (x['order'] is None, x['order']))
563 | prop = p['property']
564 | assert prop == expected_value
565 |
566 |
567 | def node_test(shape):
568 | # Check that nodes are properly linked within properties
569 | expected_value = 'http://example.org/ex#likesDogs'
570 | assert any(p['path'] == expected_value for p in shape['properties'])
571 |
572 | # Check that nodes are properly linked outside of properties
573 | expected_value = 'http://example.org/ex#likesBirds'
574 | assert any(p['path'] == expected_value for p in shape['properties'])
575 |
576 |
577 | def group_test(shape):
578 | # Check that groups are structured correctly
579 | expected_label = 'Birth & Death Date'
580 | expected_order = 0
581 | groups = shape['groups']
582 | # Labels, optional
583 | assert not any(g['label'] is None for g in groups)
584 | assert any(str(g['label']) == expected_label for g in groups)
585 | # Order, optional
586 | assert not any(g['order'] is None for g in groups)
587 | assert any(g['order'] == Literal(expected_order) for g in groups)
588 | # Contained properties
589 | for g in groups:
590 | if str(g['label']) == expected_label:
591 | assert any(p['path'] == 'http://schema.org/birthDate' for p in g['properties'])
592 |
--------------------------------------------------------------------------------