def verify(self): print('verify %s: %s' % (self.role, self.username)) utils.wait_for_replication() # reload UCR configRegistry.load() if self.mode == 'D': utils.verify_ldap_object(self.dn, should_exist=False) return utils.verify_ldap_object(self.dn, expected_attr=self.expected_attributes(), strict=True, should_exist=True) default_group_dn = 'cn=Domain Users %s,cn=groups,%s' % (self.school, self.school_base) utils.verify_ldap_object(default_group_dn, expected_attr={'uniqueMember': [self.dn], 'memberUid': [self.username]}, strict=False, should_exist=True) for school, classes in self.school_classes.iteritems(): for cl in classes: cl_group_dn = 'cn=%s,cn=klassen,cn=%s,cn=groups,%s' % (cl, cn_pupils, get_school_base(school)) utils.verify_ldap_object(cl_group_dn, expected_attr={'uniqueMember': [self.dn], 'memberUid': [self.username]}, strict=False, should_exist=True) assert self.school in self.schools for school in self.schools: role_group_dn = 'cn=%s%s,cn=groups,%s' % (self.grp_prefix, school, get_school_base(school)) utils.verify_ldap_object(role_group_dn, expected_attr={'uniqueMember': [self.dn], 'memberUid': [self.username]}, strict=False, should_exist=True) print 'person OK: %s' % self.username
def move_object(self, modulename, wait_for_replication=True, check_for_drs_replication=False, **kwargs): if not modulename: raise UCSTestUDM_MissingModulename() dn = kwargs.get('dn') if not dn: raise UCSTestUDM_MissingDn() if dn not in self._cleanup.get(modulename, set()): raise UCSTestUDM_CannotModifyExistingObject(dn) cmd = self._build_udm_cmdline(modulename, 'move', kwargs) print('Moving %s object %s' % (modulename, _prettify_cmd(cmd))) child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) (stdout, stderr) = child.communicate() if child.returncode: raise UCSTestUDM_MoveUDMObjectFailed({'module': modulename, 'kwargs': kwargs, 'returncode': child.returncode, 'stdout': stdout, 'stderr': stderr}) for line in stdout.splitlines(): # :pylint: disable-msg=E1103 if line.startswith('Object modified: '): self._cleanup.get(modulename, []).remove(dn) new_dn = ldap.dn.dn2str(ldap.dn.str2dn(dn)[0:1] + ldap.dn.str2dn(kwargs.get('position', ''))) self._cleanup.setdefault(modulename, []).append(new_dn) break else: raise UCSTestUDM_ModifyUDMUnknownDN({'module': modulename, 'kwargs': kwargs, 'stdout': stdout, 'stderr': stderr}) if wait_for_replication: utils.wait_for_replication(verbose=False) if check_for_drs_replication: if utils.package_installed('univention-samba4'): wait_for_drs_replication(ldap.filter.filter_format('cn=%s', (ldap.dn.str2dn(dn)[0][0][1],))) return new_dn
def cleanup_ou(self, ou_name, wait_for_replication=True): """ Removes the given school ou and all its corresponding objects like groups """ print '' print '*** Purging OU %s and related objects' % ou_name # remove OU specific groups for grpdn in ( 'cn=OU%(ou)s-Member-Verwaltungsnetz,cn=ucsschool,cn=groups,%(basedn)s', 'cn=OU%(ou)s-Member-Edukativnetz,cn=ucsschool,cn=groups,%(basedn)s', 'cn=OU%(ou)s-Klassenarbeit,cn=ucsschool,cn=groups,%(basedn)s', 'cn=OU%(ou)s-DC-Verwaltungsnetz,cn=ucsschool,cn=groups,%(basedn)s', 'cn=OU%(ou)s-DC-Edukativnetz,cn=ucsschool,cn=groups,%(basedn)s', 'cn=admins-%(ou)s,cn=ouadmins,cn=groups,%(basedn)s', ): grpdn = grpdn % {'ou': ou_name, 'basedn': self._ucr.get('ldap/base')} self._remove_udm_object('groups/group', grpdn) # remove OU recursively if self._ucr.is_true('ucsschool/ldap/district/enable'): oudn = 'ou=%(ou)s,ou=%(district)s,%(basedn)s' % {'ou': ou_name, 'district': ou_name[0:2], 'basedn': self._ucr.get('ldap/base')} else: oudn = 'ou=%(ou)s,%(basedn)s' % {'ou': ou_name, 'basedn': self._ucr.get('ldap/base')} self._remove_udm_object('container/ou', oudn) print '*** Purging OU %s and related objects (%s): done\n\n' % (ou_name, oudn) if wait_for_replication: utils.wait_for_replication()
def create_computerroom(self, ou_name, name=None, description=None, host_members=None, wait_for_replication=True): """ Create a room in specified OU with given attributes. If attributes are not specified, random values will be used for roomname and description. Return value: (room_name, room_dn) room_name: name of the created room room_dn: DN of the created room object """ if not ou_name: raise SchoolMissingOU('No OU name specified') # set default values if name is None: name = uts.random_name() if description is None: description = uts.random_string(length=10, numeric=False) host_members = host_members or [] if not isinstance(host_members, (list, tuple)): host_members = [host_members] kwargs = { 'school': ou_name, 'name': '%s-%s' % (ou_name, name), 'description': description, 'hosts': host_members, } print '*** Creating new room %r' % (name,) lo = self.open_ldap_connection() obj = ComputerRoom(**kwargs) result = obj.create(lo) print '*** Result of ComputerRoom(...).create(): %r' % (result,) if wait_for_replication: utils.wait_for_replication() return name, result
def import_users(self, users): line_nr = 1 param = [] def get_type_name(typ): if typ == 'cSVStudent': return 'Student' elif typ == 'cSVTeacher': return 'Teacher' elif typ == 'cSVStaff': return 'Staff' elif typ == 'cSVTeachersAndStaff': return 'Teacher and Staff' for user in users: user.update({'line': line_nr}) user.update({'type_name': get_type_name(user['type'])}) options = {'file_id': self.file_id, 'attrs': user} line_nr += 1 param.append(options) try: pprint(('Importing users with parameters=', param)) reqResult = self.client.umc_command('schoolcsvimport/import', param).result self.id_nr = reqResult['id'] utils.wait_for_replication() except FailImport: raise
def create(self, should_succeed=True): """Creates object Computer""" flavor = 'schoolwizards/computers' param = [{ 'object': { 'school': self.school, 'type': self.typ, 'name': self.name, 'ip_address': self.ip_address, 'mac_address': self.mac_address.lower(), 'subnet_mask': self.subnet_mask, 'inventory_number': self.inventory_number }, 'options': None }] print 'Creating Computer %s' % (self.name, ) print 'param = %s' % (param, ) reqResult = self.client.umc_command('schoolwizards/computers/add', param, flavor).result if reqResult[0] == should_succeed: utils.wait_for_replication() elif should_succeed in reqResult[0]['result']['message']: print 'Expected creation fail for computer (%r)\nReturn Message: %r' % ( self.name, reqResult[0]['result']['message']) else: raise CreateFail( 'Unable to create computer (%r)\nRequest Result: %r' % (param, reqResult))
def create_school_admin(self, ou_name, username=None, schools=None, firstname=None, lastname=None, mailaddress=None, is_active=True, password='******', wait_for_replication=True): position = 'cn=admins,cn=users,%s' % (self.get_ou_base_dn(ou_name)) groups = ["cn=admins-%s,cn=ouadmins,cn=groups,%s" % (ou_name, self.LDAP_BASE)] if username is None: username = uts.random_username() if firstname is None: firstname = uts.random_string(length=10, numeric=False) if lastname is None: lastname = uts.random_string(length=10, numeric=False) if mailaddress is None: mailaddress = '' kwargs = { 'school': ou_name, 'schools': schools, 'username': username, 'firstname': firstname, 'lastname': lastname, 'email': mailaddress, 'password': password, 'disabled': not(is_active), 'options': ['samba', 'ucsschoolAdministrator', 'kerberos', 'posix', 'mail'], } udm = udm_test.UCSTestUDM() dn, school_admin = udm.create_user(position=position, groups=groups, **kwargs) if wait_for_replication: utils.wait_for_replication() return school_admin, dn
def change_expired_password(self, new_password): auth_state = self._extract_auth_state() self.position = "posting change password form" print("Post SAML change password form to: %s" % self.page.url) data = { 'username': self.username, 'password': self.password, 'AuthState': auth_state, 'new_password': new_password, 'new_password_retype': new_password } self._request('POST', self.page.url, 200, data=data) self.password = new_password url = self._extract_sp_url() try: saml_msg = self._extract_saml_msg() except SamlPasswordChangeSuccess: # Samba 4 installed, S4 connector too slow to change the password utils.wait_for_replication() utils.wait_for_s4connector_replication() time.sleep(20) self._login_at_idp_with_credentials() url = self._extract_sp_url() saml_msg = self._extract_saml_msg() print('SAML message received from %s' % self.page.url) relay_state = self._extract_relay_state() self._send_saml_response_to_sp(url, saml_msg, relay_state)
def remove_object(self, modulename, wait_for_replication=True, **kwargs): if not modulename: raise UCSTestUDM_MissingModulename() dn = kwargs.get('dn') if not dn: raise UCSTestUDM_MissingDn() if dn not in self._cleanup.get(modulename, set()): raise UCSTestUDM_CannotModifyExistingObject(dn) cmd = self._build_udm_cmdline(modulename, 'remove', kwargs) print('Removing %s object %s' % (modulename, _prettify_cmd(cmd))) child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) (stdout, stderr) = child.communicate() if child.returncode: raise UCSTestUDM_RemoveUDMObjectFailed({ 'module': modulename, 'kwargs': kwargs, 'returncode': child.returncode, 'stdout': stdout, 'stderr': stderr }) if dn in self._cleanup.get(modulename, []): self._cleanup[modulename].remove(dn) if wait_for_replication: utils.wait_for_replication(verbose=False)
def create(self, expect_creation_fails_due_to_duplicated_name=False): """Creates object workgroup\n :param expect_creation_fails_due_to_duplicated_name: if user allow duplicate names no exception is raised, no group is created either :type expect_creation_fails_due_to_duplicated_name: bool """ try: createResult = self._create() if createResult and expect_creation_fails_due_to_duplicated_name: utils.fail( 'Workgroup %s already exists, though a new workgroup is created with a the same name' % self.name) utils.wait_for_replication() except HTTPError as exc: group_fullname = '%s-%s' % (self.school, self.name) exception_strings = [ 'The groupname is already in use as groupname or as username', 'Der Gruppenname wird bereits als Gruppenname oder als Benutzername verwendet', 'Die Arbeitsgruppe \'%s\' existiert bereits!' % group_fullname, 'The workgroup \'%s\' already exists!' % group_fullname ] for entry in exception_strings: if expect_creation_fails_due_to_duplicated_name and entry in str( exc.message): print('Fail : %s' % (exc)) break else: print("Exception: '%s' '%s' '%r'" % (str(exc), type(exc), exc)) raise
def __init__(self, school, role, school_classes, mode='A', username=None, firstname=None, lastname=None, password=None, mail=None, schools=None): super(User, self).__init__(school, role) if username: self.username = username self.dn = self.make_dn() if firstname: self.firstname = firstname if lastname: self.lastname = lastname if mail: self.mail = mail if school_classes: self.school_classes = school_classes self.schools = schools or [self.school] self.typ = 'teachersAndStaff' if self.role == 'teacher_staff' else self.role self.mode = mode utils.wait_for_replication() self.ucr = ucr_test.UCSTestConfigRegistry() self.ucr.load() host = self.ucr.get('ldap/master') self.client = Client(host) account = utils.UCSTestDomainAdminCredentials() admin = account.username passwd = account.bindpw self.password = password if password else passwd self.client.authenticate(admin, passwd)
def create_workgroup(self, ou_name, workgroup_name=None, description=None, users=None, wait_for_replication=True): """ Creates a new workgroup in specified ou <ou_name>. If no name for the workgroup is specified, a random name is used. <name> has to be of format "<OU>-<WGNAME>" or "<WGNAME>". Group members may also be specified a list of user DNs in <users>. """ if workgroup_name is None: workgroup_name = uts.random_username() if not workgroup_name.startswith('{}-'.format(ou_name)): workgroup_name = '{}-{}'.format(ou_name, workgroup_name) grp_dn = 'cn={},cn=schueler,cn=groups,ou={},{}'.format(workgroup_name, ou_name, self.LDAP_BASE) kwargs = { 'school': ou_name, 'name': workgroup_name, 'description': description, 'users': users or [], } print('*** Creating new WorkGroup "{}" with {}...'.format(workgroup_name, kwargs)) lo = self.open_ldap_connection() WorkGroup.invalidate_all_caches() WorkGroup.init_udm_module(lo) result = WorkGroup(**kwargs).create(lo) print('*** Result of WorkGroup(...).create(): {}'.format(result)) if wait_for_replication: utils.wait_for_replication() return workgroup_name, grp_dn
def set_members(self, new_members, options=None): """Set members for workgroup\n :param new_members: list of the new members :type new_members: list """ print 'Setting members %r from group %s' % (new_members, self.name) flavor = 'workgroup-admin' groupdn = self.dn() creationParam = [{ 'object': { '$dn$': groupdn, 'school': self.school, 'name': self.name, 'description': self.description, 'members': new_members }, 'options': options }] requestResult = self.client.umc_command('schoolgroups/put', creationParam, flavor).result if not requestResult: utils.fail('Members %s failed to be set' % new_members) else: self.members = new_members utils.wait_for_replication()
def test_ignore_user_with_functional_flag(stopped_s4_connector, udm): """Create users/user and test "functional" object flag""" # bugs: [34395] license_before = subprocess.Popen(['univention-license-check'], stdout=subprocess.PIPE).communicate()[0] # create user and check its existence user_dn = udm.create_user(check_for_drs_replication=False, wait_for=False)[0] utils.verify_ldap_object(user_dn) stdout = subprocess.Popen( [udm_test.UCSTestUDM.PATH_UDM_CLI_CLIENT, 'users/user', 'list'], stdout=subprocess.PIPE).communicate()[0] if not user_dn.lower().encode('UTF-8') in stdout.lower(): utils.fail( 'Cannot find user DN %s in output of "udm users/user list":\n%s' % (user_dn, stdout)) # perform a license check license_after = subprocess.Popen(['univention-license-check'], stdout=subprocess.PIPE).communicate()[0] if license_before == license_after: utils.fail('License check failed to detect normal user') # add 'functional' flag to user lo = utils.get_ldap_connection() lo.modify(user_dn, (('univentionObjectFlag', b'', b'functional'), )) utils.wait_for_replication() stdout = subprocess.Popen( [udm_test.UCSTestUDM.PATH_UDM_CLI_CLIENT, 'users/user', 'list'], stdout=subprocess.PIPE).communicate()[0] if user_dn.lower().encode('UTF-8') in stdout.lower(): utils.fail( '"udm users/user list" still finds user object with functional flag' ) # perform a license check license_after = subprocess.Popen(['univention-license-check'], stdout=subprocess.PIPE).communicate()[0] if license_before != license_after: utils.fail('License check detected to "functional" user') # remove 'functional' flag to user lo.modify(user_dn, (('univentionObjectFlag', b'functional', b''), )) utils.wait_for_replication() stdout = subprocess.Popen( [udm_test.UCSTestUDM.PATH_UDM_CLI_CLIENT, 'users/user', 'list'], stdout=subprocess.PIPE).communicate()[0] if not user_dn.lower().encode('UTF-8') in stdout.lower(): utils.fail( 'Cannot find user DN %s in output of "udm users/user list" after removing flag:\n%s' % (user_dn, stdout)) # perform a license check license_after = subprocess.Popen(['univention-license-check'], stdout=subprocess.PIPE).communicate()[0] if license_before == license_after: utils.fail('License check failed to detect normal user')
def test_remove_ldif(udm): dn = udm.create_object('container/cn', name=random_name(), description='will be removed') with local_ldap_down(): udm.remove_object('container/cn', dn=dn, wait_for_replication=False) verify_args = ('container/cn', dn, None) __check_action_failure(udm, verify_args) utils.wait_for_replication() udm.verify_udm_object(*verify_args)
def test_create_ldif(udm): with local_ldap_down(): dn = udm.create_object('container/cn', name=random_name(), description='has been created', wait_for_replication=False) verify_args = ('container/cn', dn, {'description': 'has been created'}) __check_action_failure(udm, verify_args) utils.wait_for_replication() udm.verify_udm_object(*verify_args)
def remove(self, options=None): """Removing a Workgroup from ldap""" print 'Removing group %s from ldap' % (self.name) groupdn = self.dn() flavor = 'workgroup-admin' removingParam = [{"object": [groupdn], "options": options}] requestResult = self.client.umc_command('schoolgroups/remove', removingParam, flavor).result if not requestResult: utils.fail('Group %s failed to be removed' % self.name) utils.wait_for_replication()
def createList(self, count): """create list of random workgroups returns list of groups objects\n :param count: number of wanted workgroups :type count: int :returns: [workgroup_object] """ print 'Creating groupList' groupList = [] for i in xrange(count): g = self.__class__(self.school) g._create() groupList.append(g) utils.wait_for_replication() return groupList
def rename_share_and_check(udm, printer, expected_value): printer_samba_name = uts.random_name() udm.modify_object('shares/printer', dn=printer, sambaName=printer_samba_name) utils.verify_ldap_object( printer, {'univentionPrinterSambaName': [printer_samba_name]}) utils.wait_for_replication() filename = '/etc/samba/printers.conf.d/%s' % printer_samba_name samba_force_printername = _testparm_is_true(filename, printer_samba_name, 'force printername') assert samba_force_printername == expected_value, "samba option \"force printername\" changed after UDM share modification" print("Ok, samba option \"force printername\" still set to %s" % (expected_value, ))
def remove(self): """Remove computer""" flavor = 'schoolwizards/computers' param = [{ 'object': { '$dn$': self.dn(), 'school': self.school, }, 'options': None }] reqResult = self.client.umc_command('schoolwizards/computers/remove', param, flavor).result if not reqResult[0]: raise RemoveFail('Unable to remove computer (%s)' % self.name) else: utils.wait_for_replication()
def modify_object(self, modulename, wait_for_replication=True, check_for_drs_replication=False, **kwargs): """ 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! :param str modulename: name of UDM module (e.g. 'users/user') """ if not modulename: raise UCSTestUDM_MissingModulename() dn = kwargs.get('dn') if not dn: raise UCSTestUDM_MissingDn() if dn not in self._cleanup.get(modulename, set()): raise UCSTestUDM_CannotModifyExistingObject(dn) cmd = self._build_udm_cmdline(modulename, 'modify', kwargs) print('Modifying %s object with %s' % (modulename, _prettify_cmd(cmd))) child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) (stdout, stderr) = child.communicate() if child.returncode: raise UCSTestUDM_ModifyUDMObjectFailed({'module': modulename, 'kwargs': kwargs, 'returncode': child.returncode, 'stdout': stdout, 'stderr': stderr}) for line in stdout.splitlines(): # :pylint: disable-msg=E1103 if line.startswith('Object modified: '): dn = line.split('Object modified: ', 1)[-1] if dn != kwargs.get('dn'): print('modrdn detected: %r ==> %r' % (kwargs.get('dn'), dn)) if kwargs.get('dn') in self._cleanup.get(modulename, []): self._cleanup.setdefault(modulename, []).append(dn) self._cleanup[modulename].remove(kwargs.get('dn')) break elif line.startswith('No modification: '): raise UCSTestUDM_NoModification({'module': modulename, 'kwargs': kwargs, 'stdout': stdout, 'stderr': stderr}) else: raise UCSTestUDM_ModifyUDMUnknownDN({'module': modulename, 'kwargs': kwargs, 'stdout': stdout, 'stderr': stderr}) if wait_for_replication: utils.wait_for_replication(verbose=False) if check_for_drs_replication: if utils.package_installed('univention-samba4'): wait_for_drs_replication(ldap.filter.filter_format('cn=%s', (ldap.dn.str2dn(dn)[0][0][1],))) return dn
def edit(self, new_attributes): """Edit object computer""" flavor = 'schoolwizards/computers' param = [{ 'object': { '$dn$': self.dn(), 'name': self.name, 'school': self.school, 'type': self.typ, 'ip_address': new_attributes.get('ip_address') if new_attributes.get('ip_address') else self.ip_address, 'mac_address': new_attributes.get('mac_address').lower() if new_attributes.get('mac_address') else self.mac_address, 'subnet_mask': new_attributes.get('subnet_mask') if new_attributes.get('subnet_mask') else self.subnet_mask, 'inventory_number': new_attributes.get('inventory_number') if new_attributes.get('inventory_number') else self.inventory_number, }, 'options': None }] print 'Editing computer %s' % (self.name, ) print 'param = %s' % (param, ) reqResult = self.client.umc_command('schoolwizards/computers/put', param, flavor).result if not reqResult[0]: raise EditFail( 'Unable to edit computer (%s) with the parameters (%r)' % (self.name, param)) else: self.ip_address = new_attributes.get('ip_address') self.mac_address = new_attributes.get('mac_address').lower() self.subnet_mask = new_attributes.get('subnet_mask') self.inventory_number = new_attributes.get('inventory_number') utils.wait_for_replication()
def create_and_verify_users(use_cli_api=True, use_python_api=False, school_name=None, nr_students=3, nr_teachers=3, nr_staff=3, nr_teacher_staff=3): assert(use_cli_api != use_python_api) print '********** Generate school data' user_import = UserImport(school_name=school_name, nr_students=nr_students, nr_teachers=nr_teachers, nr_staff=nr_staff, nr_teacher_staff=nr_teacher_staff) import_file = ImportFile(use_cli_api, use_python_api) print user_import print '********** Create users' import_file.run_import(user_import) utils.wait_for_replication() wait_for_s4connector() user_import.verify() print '********** Modify users' user_import.modify() import_file.run_import(user_import) utils.wait_for_replication() wait_for_s4connector() user_import.verify() print '********** Delete users' user_import.delete() import_file.run_import(user_import) utils.wait_for_replication() wait_for_s4connector() user_import.verify()
def create_object(self, modulename, wait_for_replication=True, check_for_drs_replication=False, **kwargs): r""" 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!). :param str modulename: name of UDM module (e.g. 'users/user') :param bool wait_for_replication: delay return until Listener has settled. :param bool check_for_drs_replication: delay return until Samab4 has settled. :param \*\*kwargs: """ if not modulename: raise UCSTestUDM_MissingModulename() dn = None cmd = self._build_udm_cmdline(modulename, 'create', kwargs) print('Creating %s object with %s' % (modulename, _prettify_cmd(cmd))) child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) (stdout, stderr) = child.communicate() if child.returncode: raise UCSTestUDM_CreateUDMObjectFailed({'module': modulename, 'kwargs': kwargs, 'returncode': child.returncode, 'stdout': stdout, 'stderr': stderr}) # find DN of freshly created object and add it to cleanup list for line in stdout.splitlines(): # :pylint: disable-msg=E1103 if line.startswith('Object created: ') or line.startswith('Object exists: '): dn = line.split(': ', 1)[-1] if not line.startswith('Object exists: '): self._cleanup.setdefault(modulename, []).append(dn) break else: raise UCSTestUDM_CreateUDMUnknownDN({'module': modulename, 'kwargs': kwargs, 'stdout': stdout, 'stderr': stderr}) if wait_for_replication: utils.wait_for_replication(verbose=False) if check_for_drs_replication: if utils.package_installed('univention-samba4'): if "options" not in kwargs or "kerberos" in kwargs["options"]: wait_for_drs_replication(ldap.filter.filter_format('cn=%s', (ldap.dn.str2dn(dn)[0][0][1],))) return dn
def create_school_class(self, ou_name, class_name=None, description=None, users=None, wait_for_replication=True): if class_name is None: class_name = uts.random_username() if not class_name.startswith('{}-'.format(ou_name)): class_name = '{}-{}'.format(ou_name, class_name) grp_dn = 'cn={},cn=klassen,cn=schueler,cn=groups,ou={},{}'.format(class_name, ou_name, self.LDAP_BASE) kwargs = { 'school': ou_name, 'name': class_name, 'description': description, 'users': users or [], } print('*** Creating new school class "{}" with {}...'.format(class_name, kwargs)) lo = self.open_ldap_connection() SchoolClass.invalidate_all_caches() SchoolClass.init_udm_module(lo) result = SchoolClass(**kwargs).create(lo) print('*** Result of SchoolClass(...).create(): {}'.format(result)) if wait_for_replication: utils.wait_for_replication() return class_name, grp_dn
def create(self): """Creates object user""" flavor = 'schoolwizards/users' param = [{ 'object': { 'school': self.school, 'schools': self.schools, 'school_classes': self.school_classes, 'email': self.mail, 'name': self.username, 'type': self.typ, 'firstname': self.firstname, 'lastname': self.lastname, 'password': self.password }, 'options': None }] print '#### Creating user %s' % (self.username,) print '#### param = %s' % (param,) reqResult = self.client.umc_command('schoolwizards/users/add', param, flavor).result if not reqResult[0]: raise CreateFail('Unable to create user (%r)' % (param,)) else: utils.wait_for_replication()
def import_ou_with_existing_dc(use_cli_api=True, use_python_api=False): with univention.testing.ucr.UCSTestConfigRegistry() as ucr: with univention.testing.udm.UCSTestUDM() as udm: create_mail_domain(ucr, udm) dc_name = uts.random_name() dhcp_service_name = uts.random_name() dhcp_service = udm.create_object('dhcp/service', service=dhcp_service_name) dhcp_server = udm.create_object('dhcp/server', server=dc_name, superordinate=dhcp_service) dhcp_subnet_properties = { 'subnet': '10.20.30.0', 'subnetmask': '24', } dhcp_subnet1 = udm.create_object('dhcp/subnet', superordinate=dhcp_service, **dhcp_subnet_properties) default_ip = Interfaces().get_default_ip_address() dhcp_subnet_properties = { 'subnet': default_ip.ip, 'subnetmask': default_ip.prefixlen, } dhcp_subnet2 = udm.create_object('dhcp/subnet', superordinate=dhcp_service, **dhcp_subnet_properties) ou_name = uts.random_name() # creatd dc try: create_and_verify_ou( ucr, ou=ou_name, ou_displayname=None, dc=dc_name, dc_administrative=None, sharefileserver=None, singlemaster=False, noneducational_create_objects=True, district_enable=False, default_dcs=None, dhcp_dns_clearou=False, do_cleanup=False, use_cli_api=use_cli_api, use_python_api=use_python_api, ) utils.verify_ldap_object(dhcp_subnet1, should_exist=True) utils.verify_ldap_object(dhcp_subnet2, should_exist=True) # dhcp subnet2 should be copied ou_base = get_ou_base(ou=ou_name, district_enable=False) new_dhcp_service_dn = 'cn=%(ou)s,cn=dhcp,%(ou_base)s' % { 'ou': ou_name, 'ou_base': ou_base } new_dhcp_subnet2_dn = 'cn=%s,%s' % (default_ip.ip, new_dhcp_service_dn) utils.verify_ldap_object(new_dhcp_subnet2_dn, should_exist=True) # dhcp subnet1 should not be copied new_dhcp_subnet1_dn = 'cn=10.20.30.0,%s' % ( new_dhcp_service_dn) utils.verify_ldap_object(new_dhcp_subnet1_dn, should_exist=False) # dhcp server has been moved utils.verify_ldap_object('cn=%s,%s' % (dc_name, new_dhcp_service_dn), should_exist=True) utils.verify_ldap_object(dhcp_server, should_exist=False) finally: remove_ou(ou_name) utils.wait_for_replication()
def import_ou_basics(use_cli_api=True, use_python_api=False): with univention.testing.ucr.UCSTestConfigRegistry() as ucr: with univention.testing.udm.UCSTestUDM() as udm: create_mail_domain(ucr, udm) for dc_administrative in [None, 'generate']: for dc in [None, 'generate']: for singlemaster in [True, False]: for noneducational_create_object in [True, False]: for district_enable in [True, False]: for default_dcs in [ None, 'edukativ', uts.random_string() ]: for dhcp_dns_clearou in [True, False]: for sharefileserver in [ None, 'generate' ]: if singlemaster and dc == 'generate': continue if not dc and dc_administrative: continue # cannot specify administrative dc without educational dc if not noneducational_create_object and dc_administrative: print 'NOTE: cannot create administrative DC without administrative objects in LDAP' continue if sharefileserver: sharefileserver = uts.random_name( ) udm.create_object( 'computers/domaincontroller_slave', name=sharefileserver) ou_name = uts.random_name() # character set contains multiple whitespaces to increase chance to get several words charset = uts.STR_ALPHANUMDOTDASH + uts.STR_ALPHA.upper( ) + '()[]/,;:_#"+*@<>~ßöäüÖÄÜ$%&! ' ou_displayname = uts.random_string( length=random.randint(1, 50), charset=charset) try: create_and_verify_ou( ucr, ou=ou_name, ou_displayname= ou_displayname, dc=(uts.random_name() if dc else None), dc_administrative=( uts.random_name() if dc_administrative else None), sharefileserver= sharefileserver, singlemaster=singlemaster, noneducational_create_objects =noneducational_create_object, district_enable= district_enable, default_dcs=default_dcs, dhcp_dns_clearou= dhcp_dns_clearou, use_cli_api=use_cli_api, use_python_api= use_python_api, ) finally: remove_ou(ou_name) utils.wait_for_replication()
def test_settings(self, school, user, user_dn, ip_address, ucr, client): printer = uts.random_string() # Create new workgroup and assign new internet rule to it group = Workgroup(school, client, members=[user_dn]) group.create() try: global_domains = ['univention.de', 'google.de'] rule = InternetRule(typ='whitelist', domains=global_domains) rule.define() rule.assign(school, group.name, 'workgroup') self.check_internetRules(client) # Add new hardware printer add_printer(printer, school, ucr.get('hostname'), ucr.get('domainname'), ucr.get('ldap/base')) # generate all the possible combinations for (rule, printmode, sharemode) white_page = 'univention.de' rules = ['none', 'Kein Internet', 'Unbeschränkt', 'custom'] printmodes = ['default', 'all', 'none'] sharemodes = ['all', 'home'] settings = itertools.product(rules, printmodes, sharemodes) t = 120 utils.wait_for_replication() # Testing loop for i, (rule, printMode, shareMode) in enumerate(settings): period = datetime.time.strftime( (datetime.datetime.now() + datetime.timedelta(0, t)).time(), '%H:%M') print print '*** %d -(internetRule, printMode, shareMode, period) = (%r, %r, %r, %r) ----------' % ( i, rule, printMode, shareMode, period) new_settings = { 'customRule': white_page, 'printMode': printMode, 'internetRule': rule, 'shareMode': shareMode, 'period': period } self.aquire_room(client) old_settings = self.get_room_settings(client) self.set_room_settings(client, new_settings) utils.wait_for_replication_and_postrun() wait_for_s4connector() # give the CUPS and Samba server a little bit more time time.sleep(15) # check if displayed values match self.check_room_settings(client, new_settings) # old_period = old_settings['period'] partial_old_settings = { 'period': old_settings['period'], 'printMode': old_settings['printMode'], 'shareMode': old_settings['shareMode'], 'internetRule': old_settings['internetRule'] } self.check_behavior(partial_old_settings, new_settings, user, ip_address, printer, white_page, global_domains, ucr) t += 60 finally: group.remove() remove_printer(printer, school, ucr.get('ldap/base'))
def wait_replications_check_rejected_uniqueMember(existing_rejects): utils.wait_for_replication() wait_for_s4connector() check_s4_rejected(existing_rejects)