Package: pytest-inmanta
pytest-inmantaA pytest plugin to test inmanta modulesInstallationpipinstallpytest-inmantaIf you want to usepytest-inmantato test a v2 module, make sure to install the module:inmantamoduleinstall-e.UsageThis plugin provides a test fixture that can compile, export and deploy code without running an actual inmanta server.deftest_compile(project):"""Test compiling a simple model that uses std"""project.compile("""host = std::Host(name="server", os=std::linux)file = std::ConfigFile(host=host, path="/tmp/test", content="1234")""")The fixture also provides access to the model internalsassertlen(project.get_instances("std::Host"))==1assertproject.get_instances("std::Host")[0].name=="server"To the exported resourcesf=project.get_resource("std::ConfigFile")assertf.permissions==644To compiler output and mock filesystemdeftest_template(project):"""Test the evaluation of a template"""project.add_mock_file("templates","test.tmpl","{{ value }}")project.compile("""import unittestvalue = "1234"std::print(std::template("unittest/test.tmpl"))""")assertproject.get_stdout()=="1234\n"And allows deployment of specific resources# perform deployresult=project.deploy_resource_v2("std::ConfigFile",expected_status=inmanta.const.ResourceState.deployed)# assert the deploy performed no changesresult.assert_no_changes()# assert the deploy produced specific log linesresult.assert_has_logline("Calling read_resource")And dryrunresult=project.dryrun_resource_v2("testmodule::Resource")assertresult.changes=={"value":{'current':'read','desired':'write'}}# Or dryrun all resources at onceresult=project.dryrun_all()It is also possible to deploy all resources at once:results=project.deploy_all()assertresults.get_context_for("std::ConfigFile",path="/tmp/test").status==ResourceState.deployedThedryrun_allanddeploy_allfunctions return aResultobject with
some helpful auxiliary functions to assert some sanity checks.We can check if every resource on the result has the correct state:results=project.dryrun_all()results.assert_all(ResourceState.dry)It is possible to determine if every resource has the attributepurgedin its changes.
This is helpful to assert if the resources are to be created (purgedset to True) or deleted (purgedset to False):results=project.dryrun_all()results.assert_resources_have_purged()The same applies to adeploy_all:results=project.deploy_all()results.assert_all(ResourceState.deployed)To check if a deploy is successful and we achieved the desired state,
it is possible to do a dryrun after the deploy and check if there are no changes:results=project.deploy_all()results.assert_all(ResourceState.deployed)results=project.dryrun_all()results.assert_has_no_changes()For convenience, it is also possible to dryrun and deploy all resources at once.
This method also asserts that the dryruns and deploys pass the sanity checks above.
It returns aDeployResultCollectionthat aggregates theResultsfrom the dryruns and the deploy.resutls=project.dryrun_and_deploy_all(assert_create_or_delete=True)results.first_dryrun.assert_all(ResourceState.dry)results.deploy.assert_all(ResourceState.deployed)results.last_dryrun.assert_all(ResourceState.dry)Testing functions and classes defined in a v1 module is also possible
using theinmanta_pluginsfixture. The fixture exposes inmanta modules as its attributes
and imports them dynamically when accessed. For v2 modules, the recommended approach is to
just use top-level imports instead of using the fixture.deftest_example(inmanta_plugins):inmanta_plugins.testmodule.regular_function("example")This dynamism is required because the compiler resets module imports whenproject.compileis called. As a result, if you store a module in a local variable, it will not survive a
compilation. Therefore you are advised to access modules in theinmanta_pluginspackage
in a fully qualified manner (using the fixture). The following example demonstrates this.deftest_module_inequality(project,inmanta_plugins):cached_module=inmanta_plugins.testmoduleassertcached_moduleisinmanta_plugins.testmoduleproject.compile("import testmodule")assertcached_moduleisnotinmanta_plugins.testmoduleWhile you could import from theinmanta_pluginspackage directly, the fixture makes abstraction
of module reloading. Without the fixture you would be required to reimport afterproject.compile.Testing pluginsTake the following plugin as an example:# <module-name>/plugins/__init__.pyfrominmanta.pluginsimportplugin@plugindefhostname(fqdn:"string")->"string":"""Return the hostname part of the fqdn"""returnfqdn.split(".")[0]A test case, to test this plugin looks like this:# <module-name>/tests/test_hostname.pydeftest_hostname(project):host="test"fqdn=f"{host}.something.com"assertproject.get_plugin_function("hostname")(fqdn)==hostLine 3:Creates a pytest test case, which requires theprojectfixture.Line 6:Calls the functionproject.get_plugin_function(plugin_name: str): FunctionType, which returns the plugin
function namedplugin_name. As such, this line tests whetherhostis returned when the plugin functionhostnameis called with the parameterfqdn.Advanced usageBecause pytest-inmanta keepsinmanta_pluginssubmodule objects alive to support top-level imports, any stateful modules
(modules that keep state on global Python variables in the module's namespace) must define cleanup logic to reset state between
compiles. Pytest-inmanta expects such cleanup functions to be synchronous functions that live in the top-level scope (defined
on the module object, not in a class) of ainmanta_pluginssubmodule (of any depth). Their name should start with
"inmanta_reset_state" and they should not take any parameters. For example:# <module-name>/plugins/state.pyMY_STATE=set()definmanta_reset_state()->None:globalMY_STATEMY_STATE=set()Multiple cleanup functions may be defined, in which case no guaranteed call order is defined.OptionsThe following options are available.--venv: folder in which to place the virtual env for tests (will be shared by all tests), overridesINMANTA_TEST_ENV.
This options depends on symlink support. This does not work on all windows versions. On windows 10 you need to run pytest in an
admin shell. Using a fixed virtual environment can speed up running the tests.--pip-index-url: pip index to install dependencies from. Can be specified multiple times to add multiple indexes. When set, it will overwrite the system index-url even ifpip-use-system-configis set. (overridesPIP_INDEX_URL, defaults to[])--pip-pre,--no-pip-preAllow installation of pre-release package by pip or not? (overridesPIP_PRE, defaults to--install-mode != release)--pip-use-system-configAllow pytest-inmanta to use the system pip config or not? (overridesINMANTA_PIP_USE_SYSTEM_CONFIG, defaults toFalse)--use-module-in-place: makes inmanta add the parent directory of your module directory to it's directory path, instead of copying your
module to a temporary libs directory. It allows testing the current module against specific versions of dependent modules.
Using this option can speed up the tests, because the module dependencies are not downloaded multiple times.--module-repo: location to download v1 modules from, overridesINMANTA_MODULE_REPO. The default value is the inmanta github organisation.
Multiple repos can be passed by space-separating them or by passing the parameter multiple times.--install-mode: install mode to use for v1 modules downloaded during this test, overridesINMANTA_INSTALL_MODE.--no-load-plugins: Don't load plugins in the Project class. OverridesINMANTA_NO_LOAD_PLUGINS.
When not using this option during the testing of plugins with theproject.get_plugin_functionmethod,
it's possible that the module'splugin/__init__.pyis loaded multiple times,
which can cause issues when it has side effects, as they are executed multiple times as well.--no-strict-deps-check: option to run pytest-inmanta using the legacy check(less strict) on requirements. By default the new strict will be used.Use the generic pytest options--log-cli-levelto show Inmanta logger to see any setup or cleanup warnings. For example,--log-cli-level=INFOCompatibility with pytest-covThe--use-module-in-placeoption should be set when pytest-inmanta is used in combination with thepytest-covpytest plugin. Without the--use-module-in-placeoption, the reported test coverage will be incorrect.Using the pytest option frameworkThepytest-inmantaextension contains a framework to help create pytest options to use in your test suite or test extension.  Options/parameters created with the framework will automatically be registered and picked up by pytest.Each option can be set via cli argument or via environment variable.  If both are set, the cli argument value takes precedence over the environment variable.When creating a new option, pay attention to place it in a place that will always be loaded by pytest, e.g. theconftest.pyfile.The different type of test parameters that can be used are shown here:pytest_inmanta/test_parameters.  The currently supported types are:BooleanTestParameterEnumTestParameterFloatTestParameterIntegerTestParameterListTestParameterPathTestParameterStringTestParameterYou can of course add and use your own option type, as long as it extends the base classTestParameterproperly.