univention.testing package
Contents
univention.testing package¶
Subpackages¶
- univention.testing.format package
- univention.testing.selenium package
- univention.testing.ucsschool package
- Submodules
- univention.testing.ucsschool.acl module
- univention.testing.ucsschool.computerroom module
- univention.testing.ucsschool.conftest module
- univention.testing.ucsschool.distribution module
- univention.testing.ucsschool.exam module
- univention.testing.ucsschool.import_factory_test_classes module
- univention.testing.ucsschool.importcomputers module
- univention.testing.ucsschool.importgroups module
- univention.testing.ucsschool.importnetworks module
- univention.testing.ucsschool.importou module
- univention.testing.ucsschool.importprinters module
- univention.testing.ucsschool.importusers module
- univention.testing.ucsschool.importusers_cli_v2 module
- univention.testing.ucsschool.importusers_http module
- univention.testing.ucsschool.internetrule module
- univention.testing.ucsschool.kelvin_api module
- univention.testing.ucsschool.klasse module
- univention.testing.ucsschool.radius module
- univention.testing.ucsschool.randomdomain module
- univention.testing.ucsschool.school module
- univention.testing.ucsschool.schoolroom module
- univention.testing.ucsschool.simplecurl module
- univention.testing.ucsschool.test_samba4 module
- univention.testing.ucsschool.ucs_test_school module
- univention.testing.ucsschool.user module
- univention.testing.ucsschool.workgroup module
Submodules¶
univention.testing.apptest module¶
- class univention.testing.apptest.Session(display_num, base_url, screenshot_path, driver)[source]¶
Bases:
object
- univention.testing.apptest.config()[source]¶
Test wide Configuration aka UCR Used to get some defaults if not environment variables are given. But if UCR is not avaiable, returns an empty dict…
- univention.testing.apptest.udm(hostname, config, admin_username, admin_password)[source]¶
A UDM instance (REST client)
- univention.testing.apptest.selenium_screenshot_path()[source]¶
Path where selenium should save screenshots
univention.testing.codes module¶
Public interface for test resultes.
- class univention.testing.codes.TestCodes[source]¶
Bases:
object
Public interface for test resultes.
- RESULT_OKAY = 0¶
- RESULT_FAIL = 1¶
- RESULT_SKIP = 77¶
- MESSAGE = {None: 'Test failed', 77: 'Test skipped', 100: 'Test passed', 101: 'Test passed', 102: 'Test passed', 110: 'Test failed', 111: 'Test failed', 120: 'Test failed', 121: 'Test failed', 122: 'Test failed', 130: 'Test failed', 131: 'Test skipped (wrong version)', 132: 'Test skipped (version too old)', 133: 'Test skipped (version too new)', 134: 'Test skipped (role mismatch)', 135: 'Test skipped (system not joined)', 136: 'Test skipped (system is joined)', 137: 'Test skipped (missing software)', 138: 'Test skipped (conflicting software)', 139: 'Test skipped (too dangerous)', 140: 'Test failed', 141: 'Test failed'}¶
- COLOR = {None: 'RED', 77: 'BLUE', 100: 'GREEN', 101: 'GREEN', 102: 'GREEN', 110: 'RED', 111: 'RED', 120: 'RED', 121: 'RED', 122: 'RED', 130: 'RED', 131: 'BLUE', 132: 'BLUE', 133: 'BLUE', 134: 'BLUE', 135: 'BLUE', 136: 'BLUE', 137: 'BLUE', 138: 'BLUE', 139: 'BLUE', 140: 'RED', 141: 'RED'}¶
- EOFS = {0: 'O', 1: 'F', 77: 'S', None: 'E', 100: 'O', 101: 'O', 102: 'O', 110: 'F', 111: 'F', 120: 'F', 121: 'F', 122: 'E', 130: 'S', 131: 'S', 132: 'S', 133: 'S', 134: 'S', 135: 'S', 136: 'S', 137: 'S', 138: 'S', 139: 'S', 140: 'E', 141: 'S'}¶
- MAX_MESSAGE_LEN = 35¶
- REASON_ABORT = 141¶
- REASON_DANGER = 139¶
- REASON_FAIL = 110¶
- REASON_FAIL_EXPECTED = 121¶
- REASON_FAIL_TRANSIENT = 120¶
- REASON_FAIL_UNEXPECTED = 111¶
- REASON_FIXED_EXPECTED = 101¶
- REASON_FIXED_UNEXPECTED = 102¶
- REASON_IMMATURE = 130¶
- REASON_INSTALL = 137¶
- REASON_INSTALLED = 138¶
- REASON_INTERNAL = 140¶
- REASON_JOIN = 135¶
- REASON_JOINED = 136¶
- REASON_OKAY = 100¶
- REASON_ROLE_MISMATCH = 134¶
- REASON_SKIP = 77¶
- REASON_UNAVAILABLE = 122¶
- REASON_UNKNOWN = None¶
- REASON_VERSION_MISMATCH = 131¶
- REASON_VERSION_TOO_NEW = 133¶
- REASON_VERSION_TOO_OLD = 132¶
univention.testing.conftest module¶
conftest plugin for pytest runner in ucs-test
univention.testing.connector_common module¶
- univention.testing.connector_common.random_string(length=10, alpha=False, numeric=False, charset='', encoding='utf-8')[source]¶
- univention.testing.connector_common.random_bytestring(length=10, alpha=False, numeric=False, charset='')[source]¶
- univention.testing.connector_common.normalize_dn(dn)[source]¶
Normalize a given dn. This removes some escaping of special chars in the DNs. Note: The CON-LDAP returns DNs with escaping chars, OpenLDAP does not.
>>> normalize_dn(r"cn=peter\#,cn=groups") 'cn=peter#,cn=groups'
- class univention.testing.connector_common.TestUser(user, rename={}, container=None, selection=None)[source]¶
Bases:
object
- class univention.testing.connector_common.TestGroup(group, rename={}, container=None)[source]¶
Bases:
object
- univention.testing.connector_common.map_udm_user_to_con(user)[source]¶
Map a UDM user given as a dictionary of property:values mappings to a dictionary of attributes:values mappings as required by the CON-LDAP. Note: This expects the properties from the UDM users/user module and not OpenLDAP-attributes!.
- univention.testing.connector_common.map_udm_group_to_con(group)[source]¶
Map a UDM group given as a dictionary of property:values mappings to a dictionary of attributes:values mappings as required by the CON-LDAP. Note: This expects the properties from the UDM groups/group module and not OpenLDAP-attributes!.
- univention.testing.connector_common.delete_udm_user(udm, con, udm_user_dn, con_user_dn, wait_for_sync)[source]¶
- univention.testing.connector_common.delete_con_user(con, con_user_dn, udm_user_dn, wait_for_sync)[source]¶
univention.testing.coverage module¶
Code coverage measurement for ucs-test
- class univention.testing.coverage.Coverage(options)[source]¶
Bases:
object
- COVERAGE_PTH = '/usr/lib/python3/dist-packages/ucstest-coverage.pth'¶
- COVERAGE_PTH_CONTENT = 'import univention.testing.coverage; univention.testing.coverage.Coverage.startup()'¶
- COVERAGE_DEBUG_PATH = '/tmp/ucs-test-coverage'¶
- coverage = None¶
- COVERAGE_DEBUG = False¶
- start()[source]¶
Start measuring of coverage. Only called by ucs-test-framework once. Sets up the configuration.
- restart_python_services()[source]¶
Restart currently running python services, so that they start/stop measuring code
- stop()[source]¶
Stop coverage measuring. Only called by ucs-test-framework once. Stores the results.
univention.testing.data module¶
Test case, environment, result and related classes.
- class univention.testing.data.TestEnvironment(interactive=True, logfile=None)[source]¶
Bases:
object
Test environment for running test cases.
Handels system data, requirements checks, test output.
- logger = <Logger test.env (WARNING)>¶
- class univention.testing.data.TestCase(filename)[source]¶
Bases:
object
Test case.
- logger = <Logger test.case (WARNING)>¶
- RE_NL = re.compile(b'[\\r\\n]+')¶
- class univention.testing.data.TestResult(case, environment=None)[source]¶
Bases:
object
Test result from running a test case.
univention.testing.debian_package module¶
- exception univention.testing.debian_package.BuildRuntimeError[source]¶
Bases:
RuntimeError
- exception univention.testing.debian_package.InstallRuntimeError[source]¶
Bases:
RuntimeError
- exception univention.testing.debian_package.UninstallRuntimeError[source]¶
Bases:
RuntimeError
univention.testing.decorators module¶
univention.testing.errors module¶
UCS Test errors.
univention.testing.internal module¶
Internal functions for test finding and setup.
- univention.testing.internal.get_sections()[source]¶
Return dictionary section-name -> section-directory.
- univention.testing.internal.get_tests(sections)[source]¶
Return dictionary of section -> [filenames].
- class univention.testing.internal.UCSVersion(ver)[source]¶
Bases:
object
UCS version.
>>> UCSVersion("1.0") < UCSVersion("2.0") True >>> UCSVersion("1.0") < UCSVersion("1.0") False >>> UCSVersion("1.0") <= UCSVersion("1.0") True >>> UCSVersion("2.0") <= UCSVersion("1.0") False >>> UCSVersion("1.0") == UCSVersion("1.0") True >>> UCSVersion("1.0") == UCSVersion("2.0") False >>> UCSVersion("1.0") != UCSVersion("2.0") True >>> UCSVersion("1.0") != UCSVersion("1.0") False >>> UCSVersion("1.0") >= UCSVersion("1.0") True >>> UCSVersion("1.0") >= UCSVersion("2.0") False >>> UCSVersion("2.0") > UCSVersion("1.0") True >>> UCSVersion("1.0") > UCSVersion("1.0") False >>> UCSVersion("1.0") == UCSVersion((1, 0, INF, INF)) True >>> UCSVersion("1.0-0-0") == UCSVersion((1, 0, 0, 0)) True >>> UCSVersion("") Traceback (most recent call last): ... ValueError: Version does not match: "" >>> UCSVersion("0") Traceback (most recent call last): ... ValueError: Version does not match: "0" >>> UCSVersion("1") Traceback (most recent call last): ... ValueError: Version does not match: "1" >>> UCSVersion("1.2") UCSVersion('=1.2') >>> UCSVersion("1.2-3") UCSVersion('=1.2-3') >>> UCSVersion("1.2-3-4") UCSVersion('=1.2-3-4') >>> UCSVersion("1.2-3-4-5") Traceback (most recent call last): ... ValueError: Version does not match: "1.2-3-4-5" >>> UCSVersion(None) Traceback (most recent call last): ... TypeError: None >>> UCSVersion(1) Traceback (most recent call last): ... TypeError: 1 >>> UCSVersion(1.5) Traceback (most recent call last): ... TypeError: 1.5
- RE_VERSION = re.compile('^(<|<<|<=|=|==|>=|>|>>)?([1-9][0-9]*)\\.([0-9]+)(?:-([0-9]*)(?:-([0-9]+))?)?$')¶
univention.testing.ldif module¶
This program compares LDAP host entries with a local comparative ldif file. All differences will be displayed at the console.
- class univention.testing.ldif.Ldif(src, exclude={'createTimestamp', 'creatorsName', 'entryCSN', 'entryUUID', 'modifiersName', 'modifyTimestamp', 'structuralObjectClass'})[source]¶
Bases:
object
Abstract class for LDIF source.
- RE = re.compile('\n\t\t^\n\t\t(?:\n\t\t\t([0-9]+(?:\\.[0-9]+)*) # ldap-oid\n\t\t\t|([A-Za-z][\\-0-9A-Za-z]*) # AttributeType\n\t\t) # AttributeDescription\n\t\t(;[\\-0-9A-Za-z]+)* # OPTIONS\n\t\t:\n\t\t(?:\n\t\t\, re.VERBOSE)¶
- OPERATIONAL = {'createTimestamp', 'creatorsName', 'entryCSN', 'entryUUID', 'modifiersName', 'modifyTimestamp', 'structuralObjectClass'}¶
- split(line)[source]¶
Split attribute and value. Options are stripped. Base64 encoded values are decoded.
- Parameters
line (str) – The line to split.
- Returns
A tuple (name, value).
>>> Ldif(b'').split('a:') == ('a', u'') True >>> Ldif(b'').split('a: b') == ('a', u'b') True >>> Ldif(b'').split('a:: YWFh') == ('a', u'aaa') True >>> Ldif(b'').split('a;b:c') == ('a', u'c') True >>> Ldif(b'').split('a;b;c::YWFh') == ('a', u'aaa') True >>> Ldif(b'').split('a:: ACB/') == ('a', u'\\u0000 \\u007f') True
- class univention.testing.ldif.LdifFile(filename)[source]¶
Bases:
object
LDIF source from local file.
- class univention.testing.ldif.LdifSlapcat[source]¶
Bases:
object
LDIF source from local LDAP.
- wait_for_data(proc)[source]¶
Wait for the remote process to send data.
>>> LdifSlapcat().wait_for_data(subprocess.Popen(('echo',), stdout=subprocess.PIPE)) >>> LdifSlapcat().wait_for_data(subprocess.Popen(('false',), stdout=subprocess.PIPE)) Traceback (most recent call last): ... SlapError: ('Error executing', ['slapcat', '-d0'], 1)
- class univention.testing.ldif.LdifSsh(hostname, ssh='ssh')[source]¶
Bases:
univention.testing.ldif.LdifSlapcat
LDIF source from remote LDAP.
- univention.testing.ldif.stream2object(ldif)[source]¶
Convert LDIF stream to dictionary of objects.
- Parameters
ldif (Ldif) – A LDIF stream.
- Returns
A dictionary mapping distinguished names to a dictionary of key-values.
>>> stream2object([{'dn': ['dc=test']}]) {'dc=test': {}}
- univention.testing.ldif.sort_dn(dname)[source]¶
Sort by reversed dn.
- Parameters
dname (str) – distinguished name.
- Returns
tuple of relative distinguised names.
>>> sort_dn('a=1') (('a=1',),) >>> sort_dn('b=1,a=1') (('a=1',), ('b=1',)) >>> sort_dn('b=2+a=1') (('a=1', 'b=2'),)
- univention.testing.ldif.compare_ldif(lldif, rldif, options)[source]¶
Compare two LDIF files.
- Parameters
ldif1 – first LDIF to compare.
ldif2 – second LDIF to compare.
options – command line options.
- univention.testing.ldif.compare_keys(ldata, rdata)[source]¶
Compare and return attributes of two LDAP objects.
- Parameters
- Returns
an iterator of differences as 3-tuples (comparison, key, value).
>>> list(compare_keys({}, {})) [] >>> list(compare_keys({'a': ['1']}, {})) [(-1, 'a', '1')] >>> list(compare_keys({}, {'a': ['1']})) [(1, 'a', '1')] >>> list(compare_keys({'a': ['1']}, {'a': ['1']})) [(0, 'a', '1')] >>> list(compare_keys({'a': ['1']}, {'a': ['2']})) [(1, 'a', '2'), (-1, 'a', '1')]
- univention.testing.ldif.compare_values(attr, lvalues, rvalues)[source]¶
Compare and return values of two multi-valued LDAP attributes.
- Parameters
- Returns
an iterator of differences as 3-tuples (comparison, key, value), where comparison<0 if key is missing in lvalues, comparison>0 if key is missing in rvalues, otherwise 0.
>>> list(compare_values('attr', [], [])) [] >>> list(compare_values('attr', ['1', '2'], ['2', '3'])) [(1, 'attr', '3'), (0, 'attr', '2'), (-1, 'attr', '1')]
univention.testing.license_client module¶
A tool to obtain licenses for the UCS test environments.
- exception univention.testing.license_client.CredentialsMissing[source]¶
Bases:
Exception
A custom exception to be raised when a ‘license.secret’ file is not found
- class univention.testing.license_client.ShopParser(log)[source]¶
Bases:
html.parser.HTMLParser
Initialize and reset this instance.
If convert_charrefs is True (the default), all character references are automatically converted to the corresponding Unicode characters.
- class univention.testing.license_client.TestLicenseClient(parser=None)[source]¶
Bases:
object
Class constructor for the test license client and HTMLParser
- create_connection()[source]¶
Creates a HTTPS connection instance on a default port (443) to the ‘self.license_server_url’
- close_connection()[source]¶
Closes the license server connection if the connection instance was created
- get_server_password(secret_file='/etc/license.secret')[source]¶
Opens and reads the ‘secret_file’. Saves the result to a ‘self.server_password’
- get_cookie()[source]¶
Makes a POST request with ‘self.server_username’ and ‘self.server_password’ into login forms and saves the cookie from the response received.
- make_post_request(url, body, headers)[source]¶
Makes a POST request with the given ‘url’, ‘body’, ‘headers’ and returns the response
- make_get_request(url, headers)[source]¶
Makes a GET request with the given ‘url’, ‘headers’ and returns the response
- get_the_license(body)[source]¶
Processes the given ‘body’ with HTMLParser to find the link to a created license file and downloads the license after.
- order_a_license()[source]¶
Makes a POST request with encoded ‘self.license_params’ as a body to order a new license. Returns the response body.
- download_license_file(link_to_license)[source]¶
Downloads the license located at filename and saves it to the file ‘self.license_filename’
- update_with_parsed_args(args)[source]¶
Updates the loglevel and license filename settings if given among the parsed arguments. Merges parsed data with default license parameters.
- process_cmd_arguments()[source]¶
Populates self.parser class with positional and optional arguments and processes the user input, checks the date format and than merges it with the default values in the ‘self.license_params’ dictionary
- main(base_dn='', end_date='', server_url='', license_file='')[source]¶
A method to order and download a test license from the license server. ‘base_dn’ and ‘end_date’ should be provided if argument parser is not used. ‘server_url’ is an optional argument for the license shop server. ‘license_file’ is an optional argument for the license filename.
univention.testing.mail module¶
- class univention.testing.mail.MailSinkGuard[source]¶
Bases:
object
This class is a simple context manager that stops all attached mail sinks if the context is left.
- with MaiLSinkGuard() as msg:
sink = MailSink(……) msg.add(sink) ….use sink….
- class univention.testing.mail.MailSink(address, port, filename=None, target_dir=None, fqdn=None)[source]¶
Bases:
object
This class starts an SMTP sink on the specified address/port. Each incoming mail will be written to a single file if target_dir is used. To write all incoming mails into one file, use filename.
>>> ms = MailSink('127.0.0.1', 12345, target_dir='/tmp/') >>> ms.start() <do some stuff> >>> ms.stop()
>>> ms = MailSink('127.0.0.1', 12345, filename='/tmp/sinkfile.eml') >>> ms.start() <do some stuff> >>> ms.stop()
>>> with MailSink('127.0.0.1', 12345, filename='/tmp/sinkfile.eml') as ms: >>> <do some stuff>
univention.testing.network module¶
Networking helper that may establish connection redirection for testing network connections/configuration of different programs (e.g. postfix).
WARNING: The networking helper will install special iptables rules that may completely break routing from/to the test system. Especially if the test script does not clean up in error cases!
- exception univention.testing.network.UCSTestNetworkNoWithStatement[source]¶
Bases:
univention.testing.network.UCSTestNetwork
- message = 'NetworkRedirector has to be used via with statement!'¶
- exception univention.testing.network.UCSTestNetworkOnlyOneLoopSupported[source]¶
Bases:
univention.testing.network.UCSTestNetwork
- message = 'NetworkRedirector does support only ONE loop at a time!'¶
- class univention.testing.network.NetworkRedirector[source]¶
Bases:
object
The NetworkRedirector is able to establish port/connection redirections via iptables. It has to be used via the with-statement.
>>> with NetworkRedirector() as nethelper: >>> nethelper.add_loop('1.2.3.4', '4.3.2.1') >>> nethelper.add_redirection('1.1.1.1', 25, 60025) >>> ... >>> # the following lines are optional! NetworkRedirector does automatic cleanup! >>> nethelper.remove_loop('1.2.3.4', '4.3.2.1') >>> nethelper.remove_redirection('1.1.1.1', 25, 60025)
It is also possible to redirect all traffic to a specific port. The trailing “/0” is important, otherwise the redirection won’t work!
>>> nethelper.add_redirection('0.0.0.0/0', 25, 60025)
- BIN_IPTABLES = '/sbin/iptables'¶
- CMD_LIST_LOOP = [['/sbin/iptables', '-t', 'mangle', '%(action)s', 'OUTPUT', '-d', '%(addr1)s', '-j', 'TOS', '--set-tos', '0x04'], ['/sbin/iptables', '-t', 'nat', '%(action)s', 'OUTPUT', '-d', '%(addr1)s', '-j', 'DNAT', '--to-destination', '%(local_external_addr)s'], ['/sbin/iptables', '-t', 'nat', '%(action)s', 'POSTROUTING', '-m', 'tos', '--tos', '0x04', '-j', 'SNAT', '--to-source', '%(addr2)s'], ['/sbin/iptables', '-t', 'mangle', '%(action)s', 'OUTPUT', '-d', '%(addr2)s', '-j', 'TOS', '--set-tos', '0x08'], ['/sbin/iptables', '-t', 'nat', '%(action)s', 'OUTPUT', '-d', '%(addr2)s', '-j', 'DNAT', '--to-destination', '%(local_external_addr)s'], ['/sbin/iptables', '-t', 'nat', '%(action)s', 'POSTROUTING', '-m', 'tos', '--tos', '0x08', '-j', 'SNAT', '--to-source', '%(addr1)s']]¶
- CMD_LIST_REDIRECTION = [['/sbin/iptables', '-t', 'nat', '%(action)s', 'OUTPUT', '-p', '%(family)s', '-d', '%(remote_addr)s', '--dport', '%(remote_port)s', '-j', 'DNAT', '--to-destination', '127.0.0.1:%(local_port)s']]¶
- run_commands(cmdlist, argdict, ignore_errors=False)[source]¶
Start all commands in cmdlist and replace formatstrings with arguments in argdict.
>>> run_commands([['/bin/echo', '%(msg)s'], ['/bin/echo', 'World']], {'msg': 'Hello'})
- add_loop(addr1, addr2)[source]¶
Add connection loop for addr1 and addr2. Outgoing connections to addr1 will be redirected back to localhost. The redirected connection will appear as it comes from addr2. All outgoing traffic to addr2 will be also redirected back to localhost and will appear as it comes from addr1.
HINT: only one loop may be established at a time!
univention.testing.pytest module¶
pytest runner for ucs-test
univention.testing.strings module¶
- univention.testing.strings.random_string(length=10, alpha=True, numeric=True, charset='', encoding='utf-8')[source]¶
Get specified number of random characters (ALPHA, NUMERIC or ALPHANUMERIC). Default is an alphanumeric string of 10 characters length. A custom character set may be defined via “charset” as string. The default encoding is UTF-8. If length is 0 or negative, an empty string is returned.
- univention.testing.strings.random_name(length=10)[source]¶
create random name (1 ALPHA, 8 ALPHANUM, 1 ALPHA)
- univention.testing.strings.random_name_special_characters(length=10)[source]¶
create random name (1 UMLAUT, 2 ALPHA, 6 SPECIAL_CHARACTERS + UMLAUT, 1 UMLAUTNUM)
- univention.testing.strings.random_username(length=10)¶
create random name (1 ALPHA, 8 ALPHANUM, 1 ALPHA)
- univention.testing.strings.random_groupname(length=10)¶
create random name (1 ALPHA, 8 ALPHANUM, 1 ALPHA)
- univention.testing.strings.random_ucs_version(min_major=1, max_major=9, min_minor=0, max_minor=99, min_patchlevel=0, max_patchlevel=99)[source]¶
- univention.testing.strings.random_ip(ip_iter=<range_iterator object>)[source]¶
Returns 110 different ip addresses in the range 11.x.x.x-120.x.x.x
- univention.testing.strings.random_subnet(ip_iter=<range_iterator object>)[source]¶
Returns 110 different ip addresses in the range 11.x.x.x-120.x.x.x
univention.testing.ucr module¶
BETA VERSION
Wrapper around Univention Configuration Registry that is able to revert the UCR status after usage. For usage examples look at the end of this file.
Warning
changes to the ConfigRegistry object will also trigger the evaluation of templates and therefore changes in configuration files created by UCR!
Warning
The API is currently under development and may change before next UCS release!
- class univention.testing.ucr.UCSTestConfigRegistry(*args, **kwargs)[source]¶
Bases:
univention.config_registry.backend.ConfigRegistry
Extension to ConfigRegistry to be able to clean up after several changes to UCR variables have been done.
initialise object
univention.testing.ucs_samba module¶
- univention.testing.ucs_samba.password_policy(complexity=False, minimum_password_age=0, maximum_password_age=3)[source]¶
univention.testing.udm module¶
ALPHA VERSION
Wrapper around Univention Directory Manager CLI to simplify creation/modification of UDM objects in python. The wrapper automatically removed created objects during wrapper destruction. For usage examples look at the end of this file.
WARNING: The API currently allows only modifications to objects created by the wrapper itself. Also the deletion of objects is currently unsupported. Also not all UDM object types are currently supported.
WARNING2: The API is currently under heavy development and may/will change before next UCS release!
- class univention.testing.udm.UCSTestUDM[source]¶
Bases:
object
- PATH_UDM_CLI_SERVER = '/usr/share/univention-directory-manager-tools/univention-cli-server'¶
- PATH_UDM_CLI_CLIENT = '/usr/sbin/udm'¶
- PATH_UDM_CLI_CLIENT_WRAPPED = '/usr/sbin/udm-test'¶
- COMPUTER_MODULES = ('computers/ubuntu', 'computers/linux', 'computers/windows', 'computers/windows_domaincontroller', 'computers/domaincontroller_master', 'computers/domaincontroller_backup', 'computers/domaincontroller_slave', 'computers/memberserver', 'computers/macos', 'computers/ipmanagedclient')¶
- property LDAP_BASE¶
- property FQHN¶
- property UNIVENTION_CONTAINER¶
- property UNIVENTION_TEMPORARY_CONTAINER¶
- create_object(modulename, wait_for_replication=True, check_for_drs_replication=False, wait_for=False, **kwargs)[source]¶
Creates a LDAP object via UDM. Values for UDM properties can be passed via keyword arguments only and have to exactly match UDM property names (case-sensitive!).
- create_with_defaults(modulename, **kwargs)[source]¶
Create any object with as maximum as possible prefilled random default values
- modify_object(modulename, wait_for_replication=True, check_for_drs_replication=False, wait_for=False, **kwargs)[source]¶
Modifies a LDAP object via UDM. Values for UDM properties can be passed via keyword arguments only and have to exactly match UDM property names (case-sensitive!). Please note: the object has to be created by create_object otherwise this call will raise an exception!
- Parameters
modulename (str) – name of UDM module (e.g. ‘users/user’)
- move_object(modulename, wait_for_replication=True, check_for_drs_replication=False, wait_for=False, **kwargs)[source]¶
- wait_for(modulename, dn, wait_for_replication=True, wait_for_drs_replication=False, wait_for_s4connector=False, everything=False)[source]¶
- create_user(wait_for_replication=True, check_for_drs_replication=True, wait_for=True, **kwargs)[source]¶
Creates a user via UDM CLI. Values for UDM properties can be passed via keyword arguments only and have to exactly match UDM property names (case-sensitive!). Some properties have default values:
- remove_user(username, wait_for_replication=True)[source]¶
Removes a user object from the ldap given it’s username.
- create_group(wait_for_replication=True, check_for_drs_replication=True, **kwargs)[source]¶
Creates a group via UDM CLI. Values for UDM properties can be passed via keyword arguments only and have to exactly match UDM property names (case-sensitive!). Some properties have default values:
If “groupname” is missing, a random group name will be used.
- class univention.testing.udm.UDM[source]¶
Bases:
univention.testing.udm.UCSTestUDM
UDM interface using the REST API
- PATH_UDM_CLI_CLIENT_WRAPPED = '/usr/sbin/udm-test-rest'¶
- univention.testing.udm.verify_udm_object(module, dn, expected_properties)[source]¶
Verify an object exists with the given dn in the given UDM module with some properties. Setting expected_properties to None requires the object to not exist. :param dict expected_properties: is a dictionary of (property,value) pairs.
- Raises
AssertionError – in case of a mismatch.
univention.testing.udm_extensions module¶
- univention.testing.udm_extensions.get_extension_name(extension_type)[source]¶
Returns a valid extension name for the given extension type. >>> get_extension_name(‘hook’) ‘jcvuardfqx’ >>> get_extension_name(‘syntax’) ‘hwvkm29tde’ >>> get_extension_name(‘module’) ‘ucstest/r3jkljngcp’
- univention.testing.udm_extensions.call_cmd(cmd, fail_on_error=True)[source]¶
Calls the given cmd (list of strings).
- univention.testing.udm_extensions.call_join_script(name, fail_on_error=True)[source]¶
Calls the given join script (e.g. name=’66foobar.inst’). If fail is true, then the function fail() is called if the exitcode is not zero.
- univention.testing.udm_extensions.call_unjoin_script(name, fail_on_error=True)[source]¶
Calls the given unjoin script (e.g. name=’66foobar-uninstall.uinst’). If fail is true, then the function fail() is called if the exitcode is not zero.
- univention.testing.udm_extensions.get_syntax_buffer(name=None, identifier=None)[source]¶
Returns a UDM syntax with given name (e.g. ‘MySimpleHook’). If name is omitted, a randomly generated name is used.
- univention.testing.udm_extensions.get_hook_buffer(name=None, identifier=None)[source]¶
Returns a UDM hook with given name (e.g. ‘MySimpleHook’). If name is omitted, a randomly generated name is used.
- univention.testing.udm_extensions.get_module_buffer(name=None, identifier=None)[source]¶
Returns a UDM module with given name (e.g. ‘testing/mytest’). If name is omitted, a randomly generated name is used (‘ucstest/%(randomstring)s’).
- univention.testing.udm_extensions.get_extension_buffer(extension_type, name=None, identifier=None)[source]¶
Get UDM extension of specified type with specified name. In case the name is omitted, a random name will be used.
- univention.testing.udm_extensions.get_postinst_script_buffer(extension_type, filename, app_id=None, version_start=None, version_end=None, options=None)[source]¶
Returns a postinst script that registers the given file as UDM extension with extension type (‘hook’, ‘syntax’ or ‘module’). Optionally UNIVENTION_APP_ID, UCS version start and UCS version end may be specified.
- univention.testing.udm_extensions.get_postrm_script_buffer(extension_type, extension_name, package_name)[source]¶
Returns an postrm script that deregisters the given UDM extension. The type of the extension has to be specified (‘hook’, ‘syntax’ or ‘module’).
- univention.testing.udm_extensions.get_join_script_buffer(extension_type, filename, app_id=None, joinscript_version=1, version_start=None, version_end=None, options=None)[source]¶
Returns a join script that registers the given file as UDM extension with extension type (‘hook’, ‘syntax’ or ‘module’). Optionally a joinscript version, UNIVENTION_APP_ID, UCS version start and UCS version end may be specified.
- univention.testing.udm_extensions.get_unjoin_script_buffer(extension_type, extension_name, package_name)[source]¶
Returns an unjoin script that deregisters the given UDM extension. The type of the extension has to be specified (‘hook’, ‘syntax’ or ‘module’).
- univention.testing.udm_extensions.get_absolute_extension_filename(extension_type, filename)[source]¶
Returns the absolute path to an extentension of the given type and filename.
univention.testing.umc module¶
- class univention.testing.umc.Client(hostname=None, username=None, password=None, language=None, timeout=None, automatic_reauthentication=False)[source]¶
Bases:
univention.lib.umc.Client
- print_response = True¶
- print_request_data = True¶
- umc_command(*args, **kwargs)[source]¶
Perform generic UMC command.
- Parameters
- Returns
The UMC response.
- Return type
- request(method, path, data=None, headers=None)[source]¶
Send request to UMC server handling re-authentication.
- Parameters
- Returns
The UMC response.
- Return type
- Raises
Unauthorized – if the session expired and re-authentication was disabled.
- class univention.testing.umc.GetHtmlTagValue(tag, condition, value_name)[source]¶
Bases:
html.parser.HTMLParser
,object
Initialize and reset this instance.
If convert_charrefs is True (the default), all character references are automatically converted to the corresponding Unicode characters.
- class univention.testing.umc.ClientSaml(hostname=None, username=None, password=None, language=None, timeout=None, automatic_reauthentication=False)[source]¶
univention.testing.utils module¶
Common functions used by tests.
- class univention.testing.utils.UCSTestDomainAdminCredentials(ucr=None)[source]¶
Bases:
object
This class fetches the username, the LDAP bind DN and the password for a domain admin user account from UCR. The account may be used for testing.
>>> dummy_ucr = {'ldap/base': 'dc=example,dc=com', 'tests/domainadmin/pwdfile': '/dev/null'} >>> account = UCSTestDomainAdminCredentials(ucr=dummy_ucr) >>> account.username 'Administrator' >>> account.binddn 'uid=Administrator,cn=users,dc=example,dc=com' >>> account.bindpw ''
- univention.testing.utils.retry_on_error(func, exceptions=(<class 'Exception'>, ), retry_count=20, delay=10)[source]¶
This function calls the given function func. If one of the specified exceptions is caught, func is called again until the retry count is reached or any unspecified exception is caught. Between two calls of func retry_on_error waits for delay seconds.
- Parameters
func – function to be called
exceptions – tuple of exception classes, that cause a rerun of func
retry_count – retry the execution of func max retry_count times
delay – waiting time in seconds between two calls of func
- Returns
return value of func
- univention.testing.utils.verify_ldap_object(baseDn, expected_attr=None, strict=True, should_exist=True, retry_count=20, delay=10, primary=False, pre_check=None, pre_check_kwargs=None, not_expected_attr=None)[source]¶
Verify [non]existence and attributes of LDAP object.
- Parameters
baseDn (str) – DN of object to check
expected_attr (dict) – attributes and their values that the LDAP object is expected to have
strict (bool) – value lists of multi-value attributes must be complete
should_exist (bool) – whether the object is expected to exist
retry_count (int) – how often to retry the verification if it fails before raising an exception
delay (float) – waiting time in seconds between retries on verification failures
primary (bool) – whether to connect to the primary (DC master) instead of local LDAP (to be exact: ucr[ldap/server/name], ucr[‘ldap/server/addition’])
pre_check – function to execute before starting verification. Value should be a function object like utils.wait_for_replication.
pre_check_kwargs (dict) – dict with kwargs to pass to pre_check() call
not_expected_attr (dict) – attributes and their values that the LDAP object is NOT expected to have
- Returns
None
- Raises
LDAPObjectNotFound – when no object was found at baseDn
LDAPUnexpectedObjectFound – when an object was found at baseDn, but should_exist=False
LDAPObjectValueMissing – when a value listed in expected_attr is missing in the LDAP object
LDAPObjectUnexpectedValue – if strict=True and a multi-value attribute of the LDAP object has more values than were listed in expected_attr or an not_expected_attr was found
TypeError – if the value of pre_check is not a function object
- class univention.testing.utils.AutomaticListenerRestart[source]¶
Bases:
object
Automatically restart Univention Directory Listener when leaving the “with” block:
with AutomaticListenerRestart() as alr: with ucr_test.UCSTestConfigRegistry() as ucr: # set some ucr variables, that influence the Univention Directory Listener univention.config_registry.handler_set(['foo/bar=ding/dong'])
- class univention.testing.utils.AutoCallCommand(enter_cmd=None, exit_cmd=None, stdout=None, stderr=None)[source]¶
Bases:
object
Automatically call the given commands when entering/leaving the “with” block. The keyword arguments enter_cmd and exit_cmd are optional:
with AutoCallCommand( enter_cmd=['/etc/init.d/dovecot', 'reload'], exit_cmd=['/etc/init.d/dovecot', 'restart']) as acc: with ucr_test.UCSTestConfigRegistry() as ucr: # set some ucr variables, that influence the Univention Directory Listener univention.config_registry.handler_set(['foo/bar=ding/dong'])
In case some filedescriptors for stdout/stderr have to be passed to the executed command, they may be passed as kwarg:
with AutoCallCommand( enter_cmd=['/etc/init.d/dovecot', 'reload'], exit_cmd=['/etc/init.d/dovecot', 'restart'], stderr=open('/dev/zero', 'w')) as acc: pass
- class univention.testing.utils.FollowLogfile(logfiles, always=False)[source]¶
Bases:
object
Prints the contents of the listed files on exit of the with block if an exception occurred. Set always=True to also print them without exception. You may wish to make the server flush its logs before existing the with block. Use AutoCallCommand inside the block for that:
cmd = ('doveadm', 'log', 'reopen') with FollowLogfile(logfiles=['/var/log/syslog', '/var/log/mail.log']): with utils.AutoCallCommand(enter_cmd=cmd, exit_cmd=cmd): pass with FollowLogfile(logfiles=['/var/log/syslog'], always=True): with utils.AutoCallCommand(enter_cmd=cmd, exit_cmd=cmd): pass
- Parameters
logfiles – list of absolute filenames to read from
always – bool, if True: print logfile change also if no error occurred (default=False)
- class univention.testing.utils.ReplicationType(value)[source]¶
Bases:
enum.IntEnum
An enumeration.
- LISTENER = 1¶
- POSTRUN = 2¶
- S4C_FROM_UCS = 3¶
- S4C_TO_UCS = 4¶
- DRS = 5¶
- univention.testing.utils.wait_for_replication_from_master_openldap_to_local_samba(replication_postrun=False, ldap_filter=None, verbose=True)[source]¶
Wait for all kind of replications
- univention.testing.utils.wait_for_replication_from_local_samba_to_local_openldap(replication_postrun=False, ldap_filter=None, verbose=True)[source]¶
Wait for all kind of replications
- univention.testing.utils.wait_for(conditions=None, verbose=True)[source]¶
Wait for all kind of replications
- univention.testing.utils.get_lid()[source]¶
get_lid() returns the last processed notifier ID of univention-directory-listener.
- univention.testing.utils.wait_for_replication(verbose=True)¶
- univention.testing.utils.wait_for_replication_and_postrun(verbose=True)¶
- univention.testing.utils.wait_for_connector_replication(verbose=True)¶