univention.testing package

Subpackages

Submodules

univention.testing.apptest module

univention.testing.apptest.run_test_file(fname)[source]
univention.testing.apptest.pip_modules(modules)[source]
univention.testing.apptest.xserver()[source]
univention.testing.apptest.ffmpg_start(capture_video, display)[source]
univention.testing.apptest.ffmpg_stop(pid)[source]
univention.testing.apptest.is_local()[source]
class univention.testing.apptest.Session(display_num, base_url, screenshot_path, driver)[source]

Bases: object

add_ucs_root_ca_to_chrome_cert_store()[source]
capture(name)[source]
wait_until_clickable(css)[source]
wait_until_clickable_and_click(css)[source]
wait_until_gone(css)[source]
goto_portal()[source]
portal_login(username, password)[source]
click_portal_tile(name)[source]
switched_frame(css)[source]
get(url)[source]
get_current_url()[source]
reload()[source]
find_all(css)[source]
find_all_below(element, css)[source]
find_first(css)[source]
assert_one(css)[source]
assert_one_below(element, css)[source]
click_element(css)[source]
click_element_below(element, css)[source]
change_tab(idx)[source]
close_tab()[source]
enter_input(input_name, value)[source]
enter_input_element(css, value)[source]
enter_return(css=None)[source]
enter_shift_tab()[source]
enter_tab()[source]
drag_and_drop(source, target)[source]
send_keys(keys)[source]
save_screenshot(name)[source]
classmethod chrome(display_num, base_url, screenshot_path)[source]
classmethod running_chrome(base_url, screenshot_path)[source]
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.hostname(config)[source]

Hostname to test against

univention.testing.apptest.fqdn(config)[source]

fqdn to test against

univention.testing.apptest.admin_username(config)[source]

Username of the Admin account

univention.testing.apptest.admin_password(config)[source]

Password of the Admin account

univention.testing.apptest.umc(hostname, admin_username, admin_password)[source]
univention.testing.apptest.ucs_call(fqdn)[source]
univention.testing.apptest.ucr(umc)[source]
univention.testing.apptest.appcenter(umc, fqdn)[source]
univention.testing.apptest.udm(hostname, config, admin_username, admin_password)[source]

A UDM instance (REST client)

univention.testing.apptest.users(udm)[source]
univention.testing.apptest.new_user(users)[source]

Creates a new user and cleans up

univention.testing.apptest.db_conn()[source]

A database connection object (sqlalchemy)

univention.testing.apptest.selenium_base_url(hostname)[source]

Base URL for selenium

univention.testing.apptest.selenium_screenshot_path()[source]

Path where selenium should save screenshots

univention.testing.apptest.test_logger()[source]

Our logger instance so you can print some info for pytest

univention.testing.apptest.chrome(selenium_base_url, selenium_screenshot_path)[source]

A running chrome instance, controllable by selenium

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.conftest.pytest_addoption(parser)[source]
univention.testing.conftest.pytest_configure(config)[source]
univention.testing.conftest.pytest_runtest_setup(item)[source]
univention.testing.conftest.check_tags(item)[source]
univention.testing.conftest.check_roles(item)[source]
univention.testing.conftest.check_exposure(item)[source]

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'
univention.testing.connector_common.to_unicode(string)[source]
univention.testing.connector_common.restart_univention_cli_server()[source]
class univention.testing.connector_common.TestUser(user, rename={}, container=None, selection=None)[source]

Bases: object

classmethod to_unicode(dictionary)[source]
class univention.testing.connector_common.NormalUser(selection=None)[source]

Bases: univention.testing.connector_common.TestUser

class univention.testing.connector_common.Utf8User(selection=None)[source]

Bases: univention.testing.connector_common.TestUser

class univention.testing.connector_common.SpecialUser(selection=None)[source]

Bases: univention.testing.connector_common.TestUser

class univention.testing.connector_common.TestGroup(group, rename={}, container=None)[source]

Bases: object

classmethod to_unicode(dictionary)[source]
class univention.testing.connector_common.NormalGroup[source]

Bases: univention.testing.connector_common.TestGroup

class univention.testing.connector_common.Utf8Group[source]

Bases: univention.testing.connector_common.TestGroup

class univention.testing.connector_common.SpecialGroup[source]

Bases: univention.testing.connector_common.TestGroup

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.create_udm_user(udm, con, user, wait_for_sync)[source]
univention.testing.connector_common.delete_udm_user(udm, con, udm_user_dn, con_user_dn, wait_for_sync)[source]
univention.testing.connector_common.create_con_user(con, udm_user, wait_for_sync)[source]
univention.testing.connector_common.delete_con_user(con, con_user_dn, udm_user_dn, wait_for_sync)[source]
univention.testing.connector_common.create_udm_group(udm, con, group, wait_for_sync)[source]
univention.testing.connector_common.delete_udm_group(udm, con, udm_group_dn, con_group_dn, wait_for_sync)[source]
univention.testing.connector_common.create_con_group(con, udm_group, wait_for_sync)[source]
univention.testing.connector_common.delete_con_group(con, con_group_dn, udm_group_dn, wait_for_sync)[source]

univention.testing.coverage module

Code coverage measurement for ucs-test

exception univention.testing.coverage.MissingCoverage[source]

Bases: Exception

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.

write_config_file()[source]

Write a python .pth file which is invoked before any python process

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.

classmethod get_argument_group(parser)[source]

The option group for ucs-test-framework

classmethod is_candidate(argv)[source]
classmethod startup()[source]

Startup function which is invoked by every(!) python process during coverage measurement. If the process is relevant we start measuring coverage.

classmethod stop_measurement(start=False)[source]
classmethod debug_message(*messages)[source]
class univention.testing.coverage.StopCoverageDecorator(method)[source]

Bases: object

inDecorator = False

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)>
dump(stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Dump environment information.

tag(require={}, ignore={}, prohibit={})[source]

Update required, ignored, prohibited tags.

set_exposure(exposure)[source]

Set maximum allowed exposure level.

set_timeout(timeout)[source]

Set maximum allowed time for single test.

class univention.testing.data.TestCase(filename)[source]

Bases: object

Test case.

logger = <Logger test.case (WARNING)>
RE_NL = re.compile(b'[\\r\\n]+')
load()[source]

Load test case from stream.

load_meta()[source]
parse_meta(header)[source]
check(environment)[source]

Check if the test case should run.

pytest_check(environment)[source]
run(result)[source]

Run the test case and fill in result.

handle_shutdown(signal, _frame)[source]
class univention.testing.data.TestResult(case, environment=None)[source]

Bases: object

Test result from running a test case.

dump(stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Dump test result data.

attach(key, mime, content)[source]

Attach artifact ‘content’ of mime-type ‘mime’.

success(reason=100)[source]

Mark result as successful.

fail(reason=110)[source]

Mark result as failed.

skip(reason=140)[source]

Mark result as skipped.

check()[source]

Test conditions to run test.

run()[source]

Return test.

class univention.testing.data.TestFormatInterface(stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[source]

Bases: object

Format UCS Test result.

begin_run(environment, count=1)[source]

Called before first test.

begin_section(section)[source]

Called before each section.

begin_test(case, prefix='')[source]

Called before each test.

end_test(result)[source]

Called after each test.

end_section()[source]

Called after each section.

end_run()[source]

Called after all test.

format(result)[source]

Format single test.

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

class univention.testing.debian_package.DebianPackage(name='testdeb', version='1.0')[source]

Bases: object

Class to build simple debian packages

get_package_name()[source]
get_temp_dir()[source]
get_binary_name()[source]
create_join_script_from_buffer(joinscript_name, joinscript_buffer)[source]
create_unjoin_script_from_buffer(unjoinscript_name, unjoinscript_buffer)[source]
create_usr_share_file_from_buffer(share_filename, schema_buffer, write_mode='w')[source]
create_debian_file_from_buffer(debian_filename, debian_buffer)[source]
build()[source]
install()[source]
uninstall(purge=False)[source]
remove()[source]

univention.testing.decorators module

class univention.testing.decorators.WaitForNonzeroResultOrTimeout(func, timeout=90)[source]

Bases: object

class univention.testing.decorators.SetTimeout(func, timeout=90)[source]

Bases: object

univention.testing.decorators.setTimeout(timeout=90)[source]

univention.testing.errors module

UCS Test errors.

exception univention.testing.errors.TestError[source]

Bases: Exception

General test error.

exception univention.testing.errors.TestConditionError[source]

Bases: Exception

Error during prepaation for test.

property tests

Return failed tests.

univention.testing.internal module

Internal functions for test finding and setup.

univention.testing.internal.setup_environment()[source]

Setup runtime environment.

univention.testing.internal.setup_debug(level)[source]

Setup Python logging.

univention.testing.internal.strip_indent(text)[source]

Strip common indent.

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]+))?)?$')
match(other)[source]

Check if other matches the criterion. >>> UCSVersion(‘>1.2-3’).match(UCSVersion(‘1.2-4’)) True >>> UCSVersion(‘>1.2-3’).match(UCSVersion(‘1.2-3-4’)) False >>> UCSVersion(‘>1.2-3-5’).match(UCSVersion(‘1.2-3-4’)) False >>> UCSVersion(‘>=1.2-3’).match(UCSVersion(‘1.2-3-4’)) True

univention.testing.ldif module

This program compares LDAP host entries with a local comparative ldif file. All differences will be displayed at the console.

exception univention.testing.ldif.LdifError[source]

Bases: Exception

Error in input processing.

exception univention.testing.ldif.SlapError[source]

Bases: Exception

Error in slapcat processing.

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'}
next_line()[source]

Return line iterator.

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
static printable(value)[source]

Convert binary data to printable string.

class univention.testing.ldif.LdifSource[source]

Bases: object

classmethod create(arg, options)[source]
start_reading()[source]

Start reading the LDIF data.

class univention.testing.ldif.LdifFile(filename)[source]

Bases: object

LDIF source from local file.

classmethod create(arg, options)[source]
start_reading()[source]

Start reading the LDIF data.

class univention.testing.ldif.LdifSlapcat[source]

Bases: object

LDIF source from local LDAP.

classmethod create(arg, options)[source]
start_reading()[source]

Start reading the LDIF data.

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.

classmethod create(hostname, options)[source]
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
  • ldata (dict) – the first LDAP object.

  • rdata (dict) – the second LDAP object.

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
  • lvalues (list) – the first values.

  • rvalues (list) – the second values.

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.ldif.parse_args()[source]

Parse command line arguments.

univention.testing.ldif.main()[source]

A main()-method with options.

univention.testing.ldif.run_compare(ldif1, ldif2, options)[source]

UNIX correct error handling. Termination by signal is propagaed as signal.

Parameters
  • ldif1 – first LDIF to compare.

  • ldif2 – second LDIF to compare.

  • options – command line options.

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.

error(message)[source]
handle_starttag(tag, attrs)[source]

Method is called every time a new start tag is found in the html feed. When the link tag with ‘orders/’ attribute is found, the attribute is saved to ‘self.link_to_license’

class univention.testing.license_client.TestLicenseClient(parser=None)[source]

Bases: object

Class constructor for the test license client and HTMLParser

setup_logging()[source]

Creates and configures the logger with an INFO level

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’

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.

get_body(response)[source]
download_license_file(link_to_license)[source]

Downloads the license located at filename and saves it to the file ‘self.license_filename’

check_date_format()[source]

Checks if the ‘EndDate’ format is correct.

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….

add(sink)[source]
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>
start()[source]
stop()[source]

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.UCSTestNetwork[source]

Bases: Exception

exception univention.testing.network.UCSTestNetworkCannotDetermineExternalAddress[source]

Bases: univention.testing.network.UCSTestNetwork

exception univention.testing.network.UCSTestNetworkCmdFailed[source]

Bases: univention.testing.network.UCSTestNetwork

exception univention.testing.network.UCSTestNetworkUnknownLoop[source]

Bases: univention.testing.network.UCSTestNetwork

exception univention.testing.network.UCSTestNetworkUnknownRedirection[source]

Bases: univention.testing.network.UCSTestNetwork

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']]
revert_network_settings()[source]
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!

remove_loop(addr1, addr2, ignore_errors=False)[source]

Remove previously defined connection loop.

add_redirection(remote_addr, remote_port, local_port, family='tcp')[source]

Add new connection redirection.

Outgoing connections to <remote_addr>:<remote_port> will be redirected back to localhost:<local_port>.

remove_redirection(remote_addr, remote_port, local_port, family='tcp', ignore_errors=False)[source]

Remove previously defined connection redirection.

univention.testing.pytest module

pytest runner for ucs-test

class univention.testing.pytest.PytestRunner[source]

Bases: object

options = Namespace(inside=True)
classmethod extend_command(testcase, cmd)[source]

Add junit and other arguments to pytest

classmethod set_arguments(options)[source]

store singleton CLI arguments globally

classmethod is_pytest(test_case)[source]

indicates that the test case is a pytest test

classmethod get_argument_group(parser)[source]

The option group for ucs-test-framework

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_int(bottom_end=0, top_end=9)[source]
univention.testing.strings.random_version(elements=3)[source]
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_mac()[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.strings.random_ipv6_subnet()[source]

Returns random six blocks of an ipv6 address

univention.testing.strings.random_domain_name(length=10)[source]
univention.testing.strings.random_dns_record()[source]
univention.testing.strings.random_date()[source]
univention.testing.strings.random_time(range_hour=(0, 23))[source]
univention.testing.strings.random_email()[source]

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

ucr_update(*args)[source]
handler_set(*args)[source]
handler_unset(*args)[source]
load()[source]

call load() of superclass and save original registry values

revert_to_original_registry()[source]

revert UCR values back to original state

univention.testing.ucs_samba module

exception univention.testing.ucs_samba.DRSReplicationFailed[source]

Bases: Exception

exception univention.testing.ucs_samba.WaitForS4ConnectorTimeout[source]

Bases: Exception

univention.testing.ucs_samba.password_policy(complexity=False, minimum_password_age=0, maximum_password_age=3)[source]
univention.testing.ucs_samba.wait_for_drs_replication(*args, **kwargs)[source]
univention.testing.ucs_samba.get_available_s4connector_dc()[source]
univention.testing.ucs_samba.force_drs_replication(source_dc=None, destination_dc=None, partition_dn=None, direction='in')[source]
univention.testing.ucs_samba.wait_for_s4connector(timeout=360, delta_t=1, s4cooldown_t=5)[source]
univention.testing.ucs_samba.append_dot(verify_list)[source]

The S4-Connector appends dots to various dns records. Helper function to adjust a list.

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!

exception univention.testing.udm.UCSTestUDM_Exception[source]

Bases: Exception

exception univention.testing.udm.UCSTestUDM_MissingModulename[source]

Bases: univention.testing.udm.UCSTestUDM_Exception

exception univention.testing.udm.UCSTestUDM_MissingDn[source]

Bases: univention.testing.udm.UCSTestUDM_Exception

exception univention.testing.udm.UCSTestUDM_CreateUDMObjectFailed[source]

Bases: univention.testing.udm.UCSTestUDM_Exception

exception univention.testing.udm.UCSTestUDM_CreateUDMUnknownDN[source]

Bases: univention.testing.udm.UCSTestUDM_Exception

exception univention.testing.udm.UCSTestUDM_ModifyUDMObjectFailed[source]

Bases: univention.testing.udm.UCSTestUDM_Exception

exception univention.testing.udm.UCSTestUDM_MoveUDMObjectFailed[source]

Bases: univention.testing.udm.UCSTestUDM_Exception

exception univention.testing.udm.UCSTestUDM_NoModification[source]

Bases: univention.testing.udm.UCSTestUDM_Exception

exception univention.testing.udm.UCSTestUDM_ModifyUDMUnknownDN[source]

Bases: univention.testing.udm.UCSTestUDM_Exception

exception univention.testing.udm.UCSTestUDM_RemoveUDMObjectFailed[source]

Bases: univention.testing.udm.UCSTestUDM_Exception

exception univention.testing.udm.UCSTestUDM_CleanupFailed[source]

Bases: univention.testing.udm.UCSTestUDM_Exception

exception univention.testing.udm.UCSTestUDM_CannotModifyExistingObject[source]

Bases: univention.testing.udm.UCSTestUDM_Exception

exception univention.testing.udm.UCSTestUDM_ListUDMObjectFailed[source]

Bases: univention.testing.udm.UCSTestUDM_Exception

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')
ad_object_identifying_filter(modulename, dn)[source]
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!).

Parameters
  • modulename (str) – name of UDM module (e.g. ‘users/user’)

  • wait_for_replication (bool) – delay return until Listener has settled.

  • check_for_drs_replication (bool) – delay return until Samab4 has settled.

  • **kwargs

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]
remove_object(modulename, wait_for_replication=True, 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:

Parameters
  • position (str) – ‘cn=users,$ldap_base’

  • password (str) – ‘univention’

  • firstname (str) – ‘Foo Bar’

  • lastname (str) – <random string>

  • username (str) – <random string> If username is missing, a random user name will be used.

Returns

(dn, username)

create_ldap_user(wait_for_replication=True, check_for_drs_replication=False, **kwargs)[source]
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:

Parameters
  • position (str) – cn=users,$ldap_base

  • name (str) – <random value>

Returns

(dn, groupname)

If “groupname” is missing, a random group name will be used.

addCleanupLock(lockType, lockValue)[source]
list_objects(modulename, **kwargs)[source]
cleanup()[source]

Automatically removes LDAP objects via UDM CLI that have been created before.

stop_cli_server()[source]

restart UDM CLI server

verify_udm_object(*args, **kwargs)[source]
verify_ldap_object(*args, **kwargs)[source]
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'
stop_cli_server()[source]

restart UDM CLI server

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_package_name()[source]

returns a valid package name

univention.testing.udm_extensions.get_package_version()[source]
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.get_extension_filename(extension_type, extension_name)[source]
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.udm_extensions.get_dn_of_extension_by_name(extension_type, name)[source]

Returns a list of DNs of UDM extension objects with given type an name, or [] if no object has been found.

univention.testing.udm_extensions.remove_extension_by_name(extension_type, extension_name, fail_on_error=True)[source]

Remove all extensions of given type and name from LDAP.

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
classmethod get_test_connection(hostname=None, *args, **kwargs)[source]
umc_command(*args, **kwargs)[source]

Perform generic UMC command.

Parameters
  • path (str) – The URL path of the command after the command/ prefix.

  • options (dict) – The argument for the UMC command.

  • flavor (str) – Optional name of the UMC module flavor, e.g. users/user for UDM modules.

  • headers (dict) – Optional HTTP headers.

Returns

The UMC response.

Return type

Response

request(method, path, data=None, headers=None)[source]

Send request to UMC server handling re-authentication.

Parameters
  • method (str) – The HTTP method for the request.

  • path (str) – The URL of the request.

  • data – The message body.

  • headers (dict) – Optional HTTP headers.

Returns

The UMC response.

Return type

Response

Raises

Unauthorized – if the session expired and re-authentication was disabled.

exception univention.testing.umc.SamlLoginError[source]

Bases: Exception

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.

handle_starttag(tag, attrs)[source]
univention.testing.umc.get_html_tag_value(page, tag, condition, value_name)[source]
class univention.testing.umc.ClientSaml(hostname=None, username=None, password=None, language=None, timeout=None, automatic_reauthentication=False)[source]

Bases: univention.testing.umc.Client

authenticate(*args)[source]

Authenticate against the host and preserves the cookie. Has to be done only once (but keep in mind that the session probably expires after 10 minutes of inactivity)

Parameters
  • username (str) – A user name.

  • password (str) – The password of the user.

authenticate_saml(*args)[source]

Setup authentication using SAML.

Parameters
  • username (str) – A user name.

  • password (str) – The password of the user.

Warning

not implemented.

univention.testing.utils module

Common functions used by tests.

exception univention.testing.utils.LDAPError[source]

Bases: Exception

exception univention.testing.utils.LDAPReplicationFailed[source]

Bases: univention.testing.utils.LDAPError

exception univention.testing.utils.LDAPObjectNotFound[source]

Bases: univention.testing.utils.LDAPError

exception univention.testing.utils.LDAPUnexpectedObjectFound[source]

Bases: univention.testing.utils.LDAPError

exception univention.testing.utils.LDAPObjectValueMissing[source]

Bases: univention.testing.utils.LDAPError

exception univention.testing.utils.LDAPObjectUnexpectedValue[source]

Bases: univention.testing.utils.LDAPError

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.get_ldap_connection(admin_uldap=False, primary=False)[source]
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
univention.testing.utils.s4connector_present()[source]
univention.testing.utils.stop_s4connector()[source]
univention.testing.utils.start_s4connector()[source]
univention.testing.utils.restart_s4connector()[source]
univention.testing.utils.stop_slapd()[source]
univention.testing.utils.start_slapd()[source]
univention.testing.utils.restart_slapd()[source]
univention.testing.utils.stop_listener()[source]
univention.testing.utils.start_listener()[source]
univention.testing.utils.restart_listener()[source]
univention.testing.utils.restart_firewall()[source]
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.wait_for_drs_replication(*args, **kwargs)[source]
univention.testing.utils.wait_for_listener_replication(verbose=True)[source]
univention.testing.utils.get_lid()[source]

get_lid() returns the last processed notifier ID of univention-directory-listener.

univention.testing.utils.wait_for_listener_replication_and_postrun(verbose=True)[source]
univention.testing.utils.wait_for_s4connector_replication(verbose=True)[source]
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)
univention.testing.utils.package_installed(package)[source]
univention.testing.utils.fail(log_message=None, returncode=1)[source]
univention.testing.utils.uppercase_in_ldap_base()[source]
univention.testing.utils.is_udp_port_open(port, ip=None)[source]
univention.testing.utils.is_port_open(port, hosts=None, timeout=60)[source]

check if port is open, if host == None check hostname and 127.0.0.1

Parameters
  • port (int) – TCP port number

  • hosts (list[str] or None) – list of hostnames or localhost if hosts is None.

Returns

True if at least on host is reachable, False otherwise.

Return type

boolean