diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..1153e9c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,48 @@ +# Portions of this file contributed by NIST are governed by the +# following statement: +# +# This software was developed at the National Institute of Standards +# and Technology by employees of the Federal Government in the course +# of their official duties. Pursuant to Title 17 Section 105 of the +# United States Code, this software is not subject to copyright +# protection within the United States. NIST assumes no responsibility +# whatsoever for its use by other parties, and makes no guarantees, +# expressed or implied, about its quality, reliability, or any other +# characteristic. +# +# We would appreciate acknowledgement if the software is used. + +name: Continuous Integration + +on: + push: + branches: [ main, develop ] + pull_request: + branches: [ main, develop ] + schedule: + - cron: '15 5 * * TUE' + +jobs: + build: + + runs-on: ubuntu-latest + strategy: + matrix: + python-version: + - '3.9' + - '3.11' + + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + - name: Pre-commit Checks + run: | + pip -q install pre-commit + pre-commit run --all-files + - name: Start from clean state + run: make clean + - name: Run tests + run: make PYTHON3=python3 check diff --git a/.github/workflows/supply-chain.yml b/.github/workflows/supply-chain.yml new file mode 100644 index 0000000..206ff08 --- /dev/null +++ b/.github/workflows/supply-chain.yml @@ -0,0 +1,49 @@ +# Portions of this file contributed by NIST are governed by the +# following statement: +# +# This software was developed at the National Institute of Standards +# and Technology by employees of the Federal Government in the course +# of their official duties. Pursuant to Title 17 Section 105 of the +# United States Code, this software is not subject to copyright +# protection within the United States. NIST assumes no responsibility +# whatsoever for its use by other parties, and makes no guarantees, +# expressed or implied, about its quality, reliability, or any other +# characteristic. +# +# We would appreciate acknowledgement if the software is used. + +# This workflow uses Make to review direct dependencies of this +# repository. + +name: Supply Chain + +on: + schedule: + - cron: '15 5 * * 1,2,3,4,5' + +jobs: + build: + + runs-on: ubuntu-latest + strategy: + matrix: + python-version: + - '3.9' + - '3.11' + + steps: + - uses: actions/checkout@v3 + with: + # This enables supply chain review against only a selected + # branch. For those using the "Git-Flow" style of branching, + # the ref value should be 'develop', so an upstream dependency + # only relevant for, say, code formatting does not need to + # induce a new commit on 'main', or a release. + # https://cyberdomainontology.org/ontology/development/#branching-cdo-git-flow + ref: main + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + - name: Review dependencies + run: make check-supply-chain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..39a00e3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +*.egg-info +*.swp +.DS_Store +.git_submodule_init.done.log +.venv-pre-commit +__pycache__ +build +dist diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..e69de29 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..09d33e9 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,14 @@ +repos: + - repo: https://github.com/psf/black + rev: 23.9.1 + hooks: + - id: black + - repo: https://github.com/pycqa/flake8 + rev: 6.1.0 + hooks: + - id: flake8 + - repo: https://github.com/pycqa/isort + rev: 5.12.0 + hooks: + - id: isort + name: isort (python) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ad89f2d --- /dev/null +++ b/LICENSE @@ -0,0 +1,39 @@ +Portions of this repository contributed by NIST are governed by +the following license. + + +# NIST Software Licensing Statement + +NIST-developed software is provided by NIST as a public service. +You may use, copy, and distribute copies of the software in any +medium, provided that you keep intact this entire notice. You may +improve, modify, and create derivative works of the software or +any portion of the software, and you may copy and distribute such +modifications or works. Modified works should carry a notice +stating that you changed the software and should note the date +and nature of any such change. Please explicitly acknowledge the +National Institute of Standards and Technology as the source of +the software. + +NIST-developed software is expressly provided "AS IS." NIST MAKES +NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED, IN FACT, OR ARISING BY +OPERATION OF LAW, INCLUDING, WITHOUT LIMITATION, THE IMPLIED +WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, +NON-INFRINGEMENT, AND DATA ACCURACY. NIST NEITHER REPRESENTS NOR +WARRANTS THAT THE OPERATION OF THE SOFTWARE WILL BE UNINTERRUPTED +OR ERROR-FREE, OR THAT ANY DEFECTS WILL BE CORRECTED. NIST DOES +NOT WARRANT OR MAKE ANY REPRESENTATIONS REGARDING THE USE OF THE +SOFTWARE OR THE RESULTS THEREOF, INCLUDING BUT NOT LIMITED TO THE +CORRECTNESS, ACCURACY, RELIABILITY, OR USEFULNESS OF THE +SOFTWARE. + +You are solely responsible for determining the appropriateness of +using and distributing the software and you assume all risks +associated with its use, including but not limited to the risks +and costs of program errors, compliance with applicable laws, +damage to or loss of data, programs or equipment, and the +unavailability or interruption of operation. This software is not +intended to be used in any situation where a failure could cause +risk of injury or damage to property. The software developed by +NIST employees is not subject to copyright protection within the +United States. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..0c0f3d0 --- /dev/null +++ b/Makefile @@ -0,0 +1,94 @@ +#!/usr/bin/make -f + +# Portions of this file contributed by NIST are governed by the +# following statement: +# +# This software was developed at the National Institute of Standards +# and Technology by employees of the Federal Government in the course +# of their official duties. Pursuant to Title 17 Section 105 of the +# United States Code, this software is not subject to copyright +# protection within the United States. NIST assumes no responsibility +# whatsoever for its use by other parties, and makes no guarantees, +# expressed or implied, about its quality, reliability, or any other +# characteristic. +# +# We would appreciate acknowledgement if the software is used. + +SHELL := /bin/bash + +PYTHON3 ?= python3 + +all: \ + .venv-pre-commit/var/.pre-commit-built.log + +.PHONY: \ + check-supply-chain \ + check-supply-chain-mypy \ + check-supply-chain-pre-commit + +.git_submodule_init.done.log: \ + .gitmodules + git submodule update --init + touch $@ + +# This virtual environment is meant to be built once and then persist, even through 'make clean'. +# If a recipe is written to remove this flag file, it should first run `pre-commit uninstall`. +.venv-pre-commit/var/.pre-commit-built.log: + rm -rf .venv-pre-commit + test -r .pre-commit-config.yaml \ + || (echo "ERROR:Makefile:pre-commit is expected to install for this repository, but .pre-commit-config.yaml does not seem to exist." >&2 ; exit 1) + $(PYTHON3) -m venv \ + .venv-pre-commit + source .venv-pre-commit/bin/activate \ + && pip install \ + --upgrade \ + pip \ + setuptools \ + wheel + source .venv-pre-commit/bin/activate \ + && pip install \ + pre-commit + source .venv-pre-commit/bin/activate \ + && pre-commit install + mkdir -p \ + .venv-pre-commit/var + touch $@ + +check: \ + check-supply-chain-mypy \ + .venv-pre-commit/var/.pre-commit-built.log + $(MAKE) \ + PYTHON3=$(PYTHON3) \ + --directory tests \ + check + +# This target's dependencies potentially modify the working directory's Git state, so it is intentionally not a dependency of check. +check-supply-chain: \ + check-supply-chain-pre-commit \ + check-supply-chain-mypy + +check-supply-chain-mypy: \ + .git_submodule_init.done.log + $(MAKE) \ + PYTHON3=$(PYTHON3) \ + --directory tests \ + check-mypy + +check-supply-chain-pre-commit: \ + .venv-pre-commit/var/.pre-commit-built.log + source .venv-pre-commit/bin/activate \ + && pre-commit autoupdate + git diff \ + --exit-code \ + .pre-commit-config.yaml + +clean: + @rm -rf \ + *.egg-info \ + build \ + dist + @$(MAKE) \ + --directory tests \ + clean + @rm -f \ + .git_submodule_init.done.log diff --git a/README.md b/README.md new file mode 100644 index 0000000..0241462 --- /dev/null +++ b/README.md @@ -0,0 +1,75 @@ +# CASE Implementation Template: CLI Example + +[![Continuous Integration](https://github.com/casework/CASE-Implementation-Template-Python-CLI/actions/workflows/ci.yml/badge.svg)](https://github.com/casework/CASE-Implementation-Template-Python-CLI/actions/workflows/ci.yml) +![CASE Version](https://img.shields.io/badge/CASE%20Version-1.2.0-green) + +_(Please see the [NIST disclaimer](#disclaimer).)_ + +This template repository is provided for those looking to develop command-line utilities using ontologies within the [Cyber Domain Ontology](https://cyberdomainontology.org) ecosystem, particularly [CASE](https://caseontology.org) and [UCO](https://unifiedcyberontology.org). + +This template repository provides a [Make](https://en.wikipedia.org/wiki/Make_%28software%29)-based test workflow used in some other CASE projects. The workflow exercises this project as a command-line interface (CLI) application (under [`tests/cli/`](tests/cli/)), and as a package (under [`tests/package/`](tests/package/)). + +This is only one possible application development style, and templates are available to support other styles. See for instance: + +* [casework/CASE-Mapping-Template-Python](https://github.com/casework/CASE-Mapping-Template-Python), which demonstrates an approach based on constructing Python `dict`s and checking generated results afterwards for CASE conformance with the [CASE Validation Action](https://github.com/kchason/case-validation-action). + +Testing procedures run in _this_ repository are: + +* _GitHub Actions_: [Workflows](.github/workflows/) are defined to run testing as they would be run in a local command-line environment, reviewing on pushes and pull requests to certain branches. +* _Supply chain review_: [One workflow](.github/workflows/supply-chain.yml) checks dependencies on a schedule, confirming pinned dependencies are the latest, and loosely-pinned dependencies do not impact things like type review. +* _Type review_: `mypy --strict` reviews the package source tree and the tests directory. +* _Code style_: `pre-commit` reviews code patches in Continuous Integration testing and in local development. Running `make` will install `pre-commit` in a special virtual environment dedicated to the cloned repository instance. +* _Doctests_: Module docstrings' inlined tests are run with `pytest`. +* _CASE validation_: Unit tests that generate CASE graph files are written to run `case_validate` before considering the file "successfully" built. +* _Editable package installation_: The test suite installs the package in an "editable" mode into the virtual environment under `tests/venv/`. Activating the virtual environment (e.g. for Bash users, running `source tests/venv/bin/activate` from the repository's top source directory) enables "live code" testing. +* _Parallel Make runs_: Tests based on `make` have dependencies specified in a manner that enables `make --jobs` to run testing in parallel. +* _Directory-local Make runs_: The Makefiles are written to run regardless of the present working directory within the top source directory or the [`tests/`](tests/) directory, assuming `make check` has been run from the top source directory at least once. If a test is failing, `cd`'ing into that test's directory and running `make check` should reproduce the failure quickly and focus development effort. + + +## Usage + +To use the template, push the "Use this template" button on GitHub, and adapt files as suits your new project's needs. The README should be revised at least from its top to the "Versioning" section. Source files should be renamed and revised, and any other files with a `TODO` within it should be adjusted. + +After any revisions, running `make check` (or `make -j check`) from the top source directory should have unit tests continue to pass. + +_Below this line is sample text to use and adapt for your project. Most text above this line is meant to document the template, rather than projects using the template._ + +To install this software, clone this repository, and run `pip install .` from within this directory. (You might want to do this in a virtual environment.) + +This provides a standalone command: + +```bash +case_cli_example output.rdf +``` + +The tests build several examples of output for the command line mode, under [`tests/cli`](tests/cli/). + +The installation also provides a package to import: + +```python +import case_cli_example +help(case_cli_example.foo) +``` + + +## Versioning + +This project follows [SEMVER 2.0.0](https://semver.org/) where versions are declared. + + +## Make targets + +Some `make` targets are defined for this repository: +* `all` - Installs `pre-commit` for this cloned repository instance. +* `check` - Run unit tests. *NOTE*: The tests entail an installation of this project's source tree, including prerequisites downloaded from PyPI. +* `clean` - Remove test build files. + + +## Licensing + +Portions of this repository contributed by NIST are governed by the [NIST Software Licensing Statement](LICENSE). + + +## Disclaimer + +Participation by NIST in the creation of the documentation of mentioned software is not intended to imply a recommendation or endorsement by the National Institute of Standards and Technology, nor is it intended to imply that any specific software is necessarily the best available for the purpose. diff --git a/case_cli_example/__init__.py b/case_cli_example/__init__.py new file mode 100644 index 0000000..e2e895c --- /dev/null +++ b/case_cli_example/__init__.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 + +# Portions of this file contributed by NIST are governed by the +# following statement: +# +# This software was developed at the National Institute of Standards +# and Technology by employees of the Federal Government in the course +# of their official duties. Pursuant to Title 17 Section 105 of the +# United States Code, this software is not subject to copyright +# protection within the United States. NIST assumes no responsibility +# whatsoever for its use by other parties, and makes no guarantees, +# expressed or implied, about its quality, reliability, or any other +# characteristic. +# +# We would appreciate acknowledgement if the software is used. + +# TODO - Adapt below. + +""" +case_cli_example is a command that demonstrates making a CLI application tested with a Make-based workflow. +""" + +__version__ = "0.0.1" + + +def foo() -> str: + """ + This function is provided to demonstrate the doctests system templated in this repository. If all doctests from the package source directory are removed, the 'check-doctest' recipe in /tests/Makefile will also need to be removed, because pytest reports a failure if no tests are found. + + >>> foo() + 'x' + """ + return "x" diff --git a/case_cli_example/cli.py b/case_cli_example/cli.py new file mode 100644 index 0000000..13f37ef --- /dev/null +++ b/case_cli_example/cli.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 + +# Portions of this file contributed by NIST are governed by the +# following statement: +# +# This software was developed at the National Institute of Standards +# and Technology by employees of the Federal Government in the course +# of their official duties. Pursuant to Title 17 Section 105 of the +# United States Code, this software is not subject to copyright +# protection within the United States. NIST assumes no responsibility +# whatsoever for its use by other parties, and makes no guarantees, +# expressed or implied, about its quality, reliability, or any other +# characteristic. +# +# We would appreciate acknowledgement if the software is used. + +# TODO - Adapt below. + +import argparse +import logging + +import case_utils +from case_utils.local_uuid import local_uuid +from case_utils.namespace import NS_RDF, NS_UCO_CORE, NS_UCO_IDENTITY, NS_XSD +from rdflib import Graph, Literal, Namespace +from rdflib.util import guess_format + + +def main() -> None: + argument_parser = argparse.ArgumentParser() + argument_parser.add_argument( + "--kb-prefix", + default="kb", + help="Prefix label to use for knowledge-base individuals. E.g. with defaults, 'http://example.org/kb/Thing-1' would compact to 'kb:Thing-1'.", + ) + argument_parser.add_argument( + "--kb-prefix-iri", + default="http://example.org/kb/", + help="Prefix IRI to use for knowledge-base individuals. E.g. with defaults, 'http://example.org/kb/Thing-1' would compact to 'kb:Thing-1'.", + ) + argument_parser.add_argument("--debug", action="store_true") + argument_parser.add_argument( + "--output-format", help="Override extension-based format guesser." + ) + # The output graph is suggested as the first positional argument to + # allow for an arbitrary number of input files as the command's end. + argument_parser.add_argument( + "out_graph", + help="A self-contained RDF graph file, in the format either requested by --output-format or guessed based on extension.", + ) + argument_parser.add_argument("in_file", nargs="*", help="One or more input files.") + + args = argument_parser.parse_args() + logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO) + + # See case_utils.local_uuid._demo_uuid for how to use this to set up + # a process call that opts in to nonrandom UUIDs. Opting in is + # beneficial for generating and version-controlling example runs of + # this tool, but might not be appropriate for production operation. + case_utils.local_uuid.configure() + + # Define Namespace object to assist with generating individual nodes. + ns_kb = Namespace(args.kb_prefix_iri) + + graph = Graph() + + # Bind various prefixes to prefix-IRIs in the output graph. + # At the time of this writing, this compacts Turtle data, but does + # not induce a JSON-LD Context Dictionary. + graph.namespace_manager.bind(args.kb_prefix, ns_kb) + graph.namespace_manager.bind("uco-core", NS_UCO_CORE) + graph.namespace_manager.bind("uco-identity", NS_UCO_IDENTITY) + + # This binding should be kept, because various RDF frameworks + # disagree on whether "xs:" or "xsd:" should be the prefix, and + # conflicting usage can lead to confusion or data errors when + # multiple tools contribute to the same graph. + graph.namespace_manager.bind("xsd", NS_XSD) + + # Generate an example object. + n_example_organization = ns_kb["Organization-" + local_uuid()] + graph.add((n_example_organization, NS_RDF.type, NS_UCO_IDENTITY.Organization)) + graph.add( + (n_example_organization, NS_UCO_CORE.name, Literal("Cyber Domain Ontology")) + ) + + # Write output file. + output_format = ( + guess_format(args.out_graph) + if args.output_format is None + else args.output_format + ) + graph.serialize(destination=args.out_graph, format=output_format) + + +if __name__ == "__main__": + main() diff --git a/case_cli_example/py.typed b/case_cli_example/py.typed new file mode 100644 index 0000000..3a6cd3a --- /dev/null +++ b/case_cli_example/py.typed @@ -0,0 +1,16 @@ +# Portions of this file contributed by NIST are governed by the +# following statement: +# +# This software was developed at the National Institute of Standards +# and Technology by employees of the Federal Government in the course +# of their official duties. Pursuant to Title 17 Section 105 of the +# United States Code, this software is not subject to copyright +# protection within the United States. NIST assumes no responsibility +# whatsoever for its use by other parties, and makes no guarantees, +# expressed or implied, about its quality, reliability, or any other +# characteristic. +# +# We would appreciate acknowledgement if the software is used. + +# This file is defined to support PEP 561: +# https://www.python.org/dev/peps/pep-0561/ diff --git a/code.yaml b/code.yaml new file mode 100644 index 0000000..2111f90 --- /dev/null +++ b/code.yaml @@ -0,0 +1,39 @@ +# NIST Opensource Portal repositories categories and themes. +# +# Chose at least one category and as many themes as you think +# adequate your opensource repository. +# You are also able to provide futher details on the choices. +# For example you could do: +# categories: +# - scientific-software: +# - quantum-computing +# - theory +# The same applies to themes. +# Since scientific-software is most common it is left as default. +# Feel free to comment it with a dash if not appropriate. +# You are able to pick multiple categories and themes. +# Unlike categories there is no default theme. +# Note: Make sure to remove unwanted categories in the repository +# topics. The final topics are produced from this file and the topics. + +categories: + - scientific-software + #- simulation + #- visualization + #- ai-ml + #- build-tools + #- hpc-workflow +themes: + # - Advanced communications + # - Optical communications + # - Quantum communications + # - Bioscience + # - Buildings and Construction + # - Chemistry + # - Electronics + # - Energy + # - Environment + # - Fire + - Forensic Science + # - Health + - Information technology diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..f16663b --- /dev/null +++ b/setup.cfg @@ -0,0 +1,56 @@ +[metadata] +#TODO +name = case_cli_example +version = attr: case_cli_example.__version__ +#TODO +# author = Example Person +# author_email = person@example.org +#TODO +description = A mapping of Example Tool to CASE +license_files = LICENSE +#TODO - PyPI will need a differently-written README. +long_description = file: README.md +long_description_content_type = text/markdown +#TODO +url = https://github.com/casework/CASE-Implementation-Example +classifiers = + # TODO + # Please select a Development Status in line with CASE community guidance: + # https://caseontology.org/resources/github_policies.html#development-statuses + # E.g.: + # Development Status :: 3 - Alpha + Enviroment :: Console + License :: Public Domain + Operating System :: OS Independent + Programming Language :: Python :: 3 + Topic :: Software Development :: Testing + +[options] +install_requires = + case_utils >= 0.13.0, < 0.14.0 +packages = find: +python_requires = >=3.9 + +[options.entry_points] +console_scripts = + #TODO + case_cli_example = case_cli_example.cli:main + +[options.extras_require] +testing = + case_utils[testing] + +[options.package_data] +#TODO +case_cli_example = py.typed + +[flake8] +# https://black.readthedocs.io/en/stable/guides/using_black_with_other_tools.html#flake8 +extend-ignore = + E203 + E302 + E501 + +[isort] +# https://pycqa.github.io/isort/docs/configuration/black_compatibility.html +profile = black diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..97f44de --- /dev/null +++ b/setup.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 + +# Portions of this file contributed by NIST are governed by the +# following statement: +# +# This software was developed at the National Institute of Standards +# and Technology by employees of the Federal Government in the course +# of their official duties. Pursuant to Title 17 Section 105 of the +# United States Code, this software is not subject to copyright +# protection within the United States. NIST assumes no responsibility +# whatsoever for its use by other parties, and makes no guarantees, +# expressed or implied, about its quality, reliability, or any other +# characteristic. +# +# We would appreciate acknowledgement if the software is used. + +import setuptools + +if __name__ == "__main__": + setuptools.setup() diff --git a/tests/.gitignore b/tests/.gitignore new file mode 100644 index 0000000..d85f153 --- /dev/null +++ b/tests/.gitignore @@ -0,0 +1,6 @@ +.pytest_cache +.venv.done.log +.venv_minimal.done.log +_* +venv +venv_minimal diff --git a/tests/Makefile b/tests/Makefile new file mode 100644 index 0000000..5e97583 --- /dev/null +++ b/tests/Makefile @@ -0,0 +1,89 @@ +#!/usr/bin/make -f + +# Portions of this file contributed by NIST are governed by the +# following statement: +# +# This software was developed at the National Institute of Standards +# and Technology by employees of the Federal Government in the course +# of their official duties. Pursuant to Title 17 Section 105 of the +# United States Code, this software is not subject to copyright +# protection within the United States. NIST assumes no responsibility +# whatsoever for its use by other parties, and makes no guarantees, +# expressed or implied, about its quality, reliability, or any other +# characteristic. +# +# We would appreciate acknowledgement if the software is used. + +SHELL := /bin/bash + +top_srcdir := $(shell cd .. ; pwd) + +PYTHON3 ?= python3 + +# Dependencies are listed here in desired execution-progression order. +all: + +.PHONY: \ + check-cli \ + check-mypy + +.venv.done.log: \ + $(top_srcdir)/.git_submodule_init.done.log \ + $(top_srcdir)/setup.cfg \ + $(top_srcdir)/setup.py + rm -rf venv + $(PYTHON3) -m venv \ + venv + source venv/bin/activate \ + && pip install \ + --upgrade \ + pip \ + setuptools \ + wheel + source venv/bin/activate \ + && pip install \ + --editable \ + $(top_srcdir)[testing] + touch $@ + +# Dependencies are listed here in desired execution-progression order. +check: \ + check-mypy \ + check-doctest \ + check-cli \ + check-package + +check-cli: \ + .venv.done.log + $(MAKE) \ + --directory cli \ + check + +check-doctest: \ + .venv.done.log + source venv/bin/activate \ + && pytest \ + --doctest-modules \ + --log-level=DEBUG \ + $(top_srcdir)/case_cli_example + +check-package: \ + .venv.done.log + $(MAKE) \ + --directory package \ + check + +check-mypy: \ + .venv.done.log + source venv/bin/activate \ + && mypy \ + --exclude venv \ + --strict \ + $(top_srcdir)/case_cli_example \ + . + +clean: + @rm -f \ + .venv.done.log + @rm -rf \ + venv diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..829d8d1 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,12 @@ +# Test suite + +This directory houses proof-of-functionality tests. +* [`gtime_log/`](gtime_log/) - Uses scripts in source tree to build a UCO Process object in a JSON-LD file, using only a GNU Time log file. Uses a virtual environment built without installing `case_gnu_time`. +* [`gtime_and_done_log/`](gtime_and_done_log/) - As `gtime_log/`, but using a timestamp recorded in another file tied to a process output. +* [`from_pip/`](from_pip/) - Uses virtual environment with the package `case_gnu_time` installed. (Runs [`setup.py`](../setup.py), not `pip install`.) Runs program `case_gnu_time`, producing a Process as in `gtime_log`. +* [`as_import/`](as_import/) - Uses `case_gnu_time` as an imported package to create a custom-named UCO `CyberItem` with a Process Facet. + + +## Running the test suite + +Run `make check`. `make check` should be run from one directory up, at least once, to trigger some downloads. diff --git a/tests/cli/Makefile b/tests/cli/Makefile new file mode 100644 index 0000000..94fd389 --- /dev/null +++ b/tests/cli/Makefile @@ -0,0 +1,71 @@ +#!/usr/bin/make -f + +# Portions of this file contributed by NIST are governed by the +# following statement: +# +# This software was developed at the National Institute of Standards +# and Technology by employees of the Federal Government in the course +# of their official duties. Pursuant to Title 17 Section 105 of the +# United States Code, this software is not subject to copyright +# protection within the United States. NIST assumes no responsibility +# whatsoever for its use by other parties, and makes no guarantees, +# expressed or implied, about its quality, reliability, or any other +# characteristic. +# +# We would appreciate acknowledgement if the software is used. + +SHELL := /bin/bash + +top_srcdir := $(shell cd ../.. ; pwd) + +all: \ + example_output.jsonld \ + example_output.rdf \ + example_output.ttl \ + example_output_debug.jsonld \ + example_output_debug.rdf \ + example_output_debug.ttl + +.PHONY: \ + check-pytest + +check: \ + check-pytest + +check-pytest: \ + all + source $(top_srcdir)/tests/venv/bin/activate \ + && pytest \ + --log-level=DEBUG + +clean: + @rm -rf \ + *.jsonld \ + *.rdf \ + *.ttl \ + .pytest_cache + +example_output.%: \ + $(top_srcdir)/case_cli_example/cli.py \ + $(top_srcdir)/tests/.venv.done.log + export CASE_DEMO_NONRANDOM_UUID_BASE="$(top_srcdir)" \ + && source $(top_srcdir)/tests/venv/bin/activate \ + && case_cli_example \ + _$@ + source $(top_srcdir)/tests/venv/bin/activate \ + && case_validate \ + _$@ + mv _$@ $@ + +example_output_debug.%: \ + $(top_srcdir)/case_cli_example/cli.py \ + $(top_srcdir)/tests/.venv.done.log + export CASE_DEMO_NONRANDOM_UUID_BASE="$(top_srcdir)" \ + && source $(top_srcdir)/tests/venv/bin/activate \ + && case_cli_example \ + --debug \ + _$@ + source $(top_srcdir)/tests/venv/bin/activate \ + && case_validate \ + _$@ + mv _$@ $@ diff --git a/tests/cli/example_output.jsonld b/tests/cli/example_output.jsonld new file mode 100644 index 0000000..5fc7c7c --- /dev/null +++ b/tests/cli/example_output.jsonld @@ -0,0 +1,13 @@ +[ + { + "@id": "http://example.org/kb/Organization-b7c4b9e3-a93b-53b8-8a58-243986ddc2dc", + "@type": [ + "https://ontology.unifiedcyberontology.org/uco/identity/Organization" + ], + "https://ontology.unifiedcyberontology.org/uco/core/name": [ + { + "@value": "Cyber Domain Ontology" + } + ] + } +] \ No newline at end of file diff --git a/tests/cli/example_output.rdf b/tests/cli/example_output.rdf new file mode 100644 index 0000000..3370312 --- /dev/null +++ b/tests/cli/example_output.rdf @@ -0,0 +1,10 @@ + + + + + Cyber Domain Ontology + + diff --git a/tests/cli/example_output.ttl b/tests/cli/example_output.ttl new file mode 100644 index 0000000..96629bb --- /dev/null +++ b/tests/cli/example_output.ttl @@ -0,0 +1,7 @@ +@prefix kb: . +@prefix uco-core: . +@prefix uco-identity: . + +kb:Organization-a70ee2b7-9fd8-537f-8f70-6f68805acae6 a uco-identity:Organization ; + uco-core:name "Cyber Domain Ontology" . + diff --git a/tests/cli/example_output_debug.jsonld b/tests/cli/example_output_debug.jsonld new file mode 100644 index 0000000..4c8bb03 --- /dev/null +++ b/tests/cli/example_output_debug.jsonld @@ -0,0 +1,13 @@ +[ + { + "@id": "http://example.org/kb/Organization-2ffb424f-ef33-5cc9-8185-091073051016", + "@type": [ + "https://ontology.unifiedcyberontology.org/uco/identity/Organization" + ], + "https://ontology.unifiedcyberontology.org/uco/core/name": [ + { + "@value": "Cyber Domain Ontology" + } + ] + } +] \ No newline at end of file diff --git a/tests/cli/example_output_debug.rdf b/tests/cli/example_output_debug.rdf new file mode 100644 index 0000000..8993233 --- /dev/null +++ b/tests/cli/example_output_debug.rdf @@ -0,0 +1,10 @@ + + + + + Cyber Domain Ontology + + diff --git a/tests/cli/example_output_debug.ttl b/tests/cli/example_output_debug.ttl new file mode 100644 index 0000000..8b8d038 --- /dev/null +++ b/tests/cli/example_output_debug.ttl @@ -0,0 +1,7 @@ +@prefix kb: . +@prefix uco-core: . +@prefix uco-identity: . + +kb:Organization-10639c31-bef6-57b7-9747-71171b669844 a uco-identity:Organization ; + uco-core:name "Cyber Domain Ontology" . + diff --git a/tests/cli/test_cli.py b/tests/cli/test_cli.py new file mode 100644 index 0000000..7ce2422 --- /dev/null +++ b/tests/cli/test_cli.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 + +# Portions of this file contributed by NIST are governed by the +# following statement: +# +# This software was developed at the National Institute of Standards +# and Technology by employees of the Federal Government in the course +# of their official duties. Pursuant to Title 17 Section 105 of the +# United States Code, this software is not subject to copyright +# protection within the United States. NIST assumes no responsibility +# whatsoever for its use by other parties, and makes no guarantees, +# expressed or implied, about its quality, reliability, or any other +# characteristic. +# +# We would appreciate acknowledgement if the software is used. + +from pathlib import Path +from typing import Set + +import pytest +from case_utils.namespace import NS_RDF, NS_UCO_IDENTITY +from rdflib import Graph, URIRef +from rdflib.query import ResultRow + + +@pytest.mark.parametrize( + ["filename"], + [ + ("example_output.jsonld",), + ("example_output.rdf",), + ("example_output.ttl",), + ("example_output_debug.jsonld",), + ("example_output_debug.rdf",), + ("example_output_debug.ttl",), + ], +) +def test_example_output_with_iterator(filename: str) -> None: + srcdir = Path(__file__).parent + graph = Graph() + graph.parse(srcdir / filename) + n_organizations: Set[URIRef] = set() + for n_subject in graph.subjects(NS_RDF.type, NS_UCO_IDENTITY.Organization): + assert isinstance(n_subject, URIRef) + n_organizations.add(n_subject) + assert len(n_organizations) == 1 + + +@pytest.mark.parametrize( + ["filename"], + [ + ("example_output.jsonld",), + ("example_output.rdf",), + ("example_output.ttl",), + ("example_output_debug.jsonld",), + ("example_output_debug.rdf",), + ("example_output_debug.ttl",), + ], +) +def test_example_output_with_sparql(filename: str) -> None: + srcdir = Path(__file__).parent + graph = Graph() + graph.parse(srcdir / filename) + + # This query includes a prefix statement that is typically provided + # by the data graph. However, some graph generators omit prefixes + # if they are never referenced in the triples. In that case, + # attempting to run this query without a PREFIX statement would fail + # due to an unbound prefix. While ultimately the test would be + # correct in failing, it would fail for a potentially confusing + # reason appearing to be a syntax error, rather than a real reason + # of the query having no data to find. + query = """\ +PREFIX uco-identity: +SELECT ?nOrganization +WHERE { + ?nOrganization + a uco-identity:Organization ; + . +} +""" + n_organizations: Set[URIRef] = set() + for result in graph.query(query): + assert isinstance(result, ResultRow) + assert isinstance(result[0], URIRef) + n_organizations.add(result[0]) + assert len(n_organizations) == 1 diff --git a/tests/package/Makefile b/tests/package/Makefile new file mode 100644 index 0000000..207a6d7 --- /dev/null +++ b/tests/package/Makefile @@ -0,0 +1,34 @@ +#!/usr/bin/make -f + +# Portions of this file contributed by NIST are governed by the +# following statement: +# +# This software was developed at the National Institute of Standards +# and Technology by employees of the Federal Government in the course +# of their official duties. Pursuant to Title 17 Section 105 of the +# United States Code, this software is not subject to copyright +# protection within the United States. NIST assumes no responsibility +# whatsoever for its use by other parties, and makes no guarantees, +# expressed or implied, about its quality, reliability, or any other +# characteristic. +# +# We would appreciate acknowledgement if the software is used. + +SHELL := /bin/bash + +top_srcdir := $(shell cd ../.. ; pwd) + +all: + +.PHONY: \ + check-pytest + +check: \ + check-pytest + +check-pytest: + source $(top_srcdir)/tests/venv/bin/activate \ + && pytest \ + --log-level=DEBUG + +clean: diff --git a/tests/package/test_package.py b/tests/package/test_package.py new file mode 100644 index 0000000..9dc5d33 --- /dev/null +++ b/tests/package/test_package.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 + +# Portions of this file contributed by NIST are governed by the +# following statement: +# +# This software was developed at the National Institute of Standards +# and Technology by employees of the Federal Government in the course +# of their official duties. Pursuant to Title 17 Section 105 of the +# United States Code, this software is not subject to copyright +# protection within the United States. NIST assumes no responsibility +# whatsoever for its use by other parties, and makes no guarantees, +# expressed or implied, about its quality, reliability, or any other +# characteristic. +# +# We would appreciate acknowledgement if the software is used. + +from case_cli_example import foo + + +def test_package() -> None: + assert foo() == "x"