#!/usr/share/ucs-test/runner python
## -*- coding: utf-8 -*-
## desc: Import users via CLI v2
## tags: [apptest,ucsschool,longrunning]
## roles: [domaincontroller_master]
## exposure: dangerous
## timeout: 14400
## packages:
##   - ucs-school-import

import tempfile
import json
import shutil
import logging
import copy
import sys
import random
import csv
import os
import pprint
import subprocess
from essential.importusers import Person
import univention.testing.ucr
import univention.testing.strings as uts
import univention.testing.ucsschool as utu
import univention.testing.utils as utils


class Bunch(object):
	def __init__(self, **kwds):
		self.__dict__.update(kwds)


class ImportException(Exception):
	pass


class ConfigDict(dict):
	def update_entry(self, key, value):
		"""
		update_entry('foo:bar:baz', 'my value')
		update_entry('foo:bar:ding', False)
		"""
		if isinstance(value, basestring):
			if value.lower() == 'false':
				value = False
			elif value.lower() == 'true':
				value = True
		mydict = self
		items = key.split(':')
		while items:
			if len(items) == 1:
				mydict[items[0]] = value
			else:
				mydict = mydict.setdefault(items[0], {})
			del items[0]


class PyHooks(object):
	def __init__(self, hook_basedir=None):
		self.hook_basedir = hook_basedir if hook_basedir else '/usr/share/ucs-school-import/pyhooks'
		self.tmpdir = tempfile.mkdtemp(prefix='pyhook.', dir='/tmp')
		self.cleanup_files = set()
		self.log = logging.getLogger('PyHooks')

	def create_hooks(self):
		"""
		"""
		fn = '%s.py' % (uts.random_name(),)
		data = '''from ucsschool.importer.utils.user_pyhook import UserPyHook
import os

class MyHook(UserPyHook):
	priority = {
			"pre_create": 1,
			"post_create": 1,
			"pre_modify": 1,
			"post_modify": 1,
			"pre_move": 1,
			"post_move": 1,
			"pre_remove": 1,
			"post_remove": 1
	}

	def pre_create(self, user):
			self.logger.info("Running a pre_create hook for %%s.", user)
			self.run(user, 'create', 'pre')

	def post_create(self, user):
			self.logger.info("Running a post_create hook for %%s.", user)
			self.run(user, 'create', 'post')

	def pre_modify(self, user):
			self.logger.info("Running a pre_modify hook for %%s.", user)
			self.run(user, 'modify', 'pre')

	def post_modify(self, user):
			self.logger.info("Running a post_modify hook for %%s.", user)
			self.run(user, 'modify', 'post')

	def pre_move(self, user):
			self.logger.info("Running a pre_move hook for %%s.", user)
			self.run(user, 'move', 'pre')

	def post_move(self, user):
			self.logger.info("Running a post_move hook for %%s.", user)
			self.run(user, 'move', 'post')

	def pre_remove(self, user):
			self.logger.info("Running a pre_remove hook for %%s.", user)
			self.run(user, 'remove', 'pre')

	def post_remove(self, user):
			self.logger.info("Running a post_remove hook for %%s.", user)
			self.run(user, 'remove', 'post')

	def run(self, user, action, when):
		self.logger.info("***** Running {} {} hook for user {}.".format(when, action, user))
		# udm_properties[k] is only filled from LDAP, if k was in the input
		# don't try to get_udm_object() on a user not {anymore, yet} in ldap
		if not user.udm_properties.get('organisation') and not ((action == 'create' and when == 'pre') or (action == 'remove' and when == 'post')):
			obj = user.get_udm_object(self.lo)
			user.udm_properties['organisation'] = obj.info.get('organisation', '')
		user.udm_properties['organisation'] = user.udm_properties.get('organisation', '') + ',{}-{}'.format(when, action)
		if when == 'post' and action != 'remove':
			user.modify(self.lo)
		fn_touchfile = os.path.join(%(tmpdir)r, '%%s-%%s' %% (when, action))
		open(fn_touchfile, 'w').write('EXECUTED\\n')
''' % { 'tmpdir': self.tmpdir }

		fn = os.path.join(self.hook_basedir, fn)
		self.cleanup_files.add(fn)
		with open(fn, 'w') as fd:
			fd.write(data)
		self.log.info('Created hook %r', fn)

	def cleanup(self):
		shutil.rmtree(self.tmpdir, ignore_errors=True)
		for fn in self.cleanup_files:
			try:
				os.remove(fn)
			except (IOError, OSError):
				self.log.warning('Failed to remove %r' % (fn,))
			try:
				os.remove('%sc' % fn)
			except (IOError, OSError):
				pass


class CLI_Import_v2_Tester(object):
	def __init__(self):
		self.tmpdir = tempfile.mkdtemp(prefix='34_import-users_via_cli_v2.', dir='/tmp/')
		self.log = logging.getLogger('main')
		self.lo = None
		self.ldap_status = None
		self.hook_fn_set = set()
		self.ou_A = Bunch()
		self.ou_B = Bunch()
		self.default_config = ConfigDict({
			"factory": "ucsschool.importer.default_user_import_factory.DefaultUserImportFactory",
			"classes": {},
			"input": {
				"type": "csv",
				"filename": "import.csv"
			},
			"csv": {
				"mapping": {
					"OUs": "schools",
					"Vor": "firstname",
					"Nach": "lastname",
					"Gruppen": "school_classes",
					"E-Mail": "email",
					"Beschreibung": "description",
				}
			},
			"scheme": {
				"email": "<firstname>[0].<lastname>@<maildomain>",
				"recordUID": "<firstname>;<lastname>;<email>",
				"username": {
					"allow_rename": False,
					"default": "<:umlauts><firstname>[0].<lastname>[COUNTER2]"
				},
			},
			"sourceUID": "sourceDB",
			"user_role": "student",
			"tolerate_errors": 0,
		})

	def cleanup(self):
		self.log.info('Purging %r', self.tmpdir)
		shutil.rmtree(self.tmpdir, ignore_errors=True)
		for hook_fn in self.hook_fn_set:
			try:
				os.remove(hook_fn)
			except (IOError, OSError):
				self.log.warning('Failed to remove %r' % (hook_fn,))

	def create_config_json(self, values=None, config=None):
		"""
		Creates a config file for "ucs-school-user-import".
		Default values may be overridden via a dict called values.
		>>> values = {'user_role': 'teacher',
					  'input:type': 'csv' }
		>>> create_config_json(values=values)
		'/tmp/config.dkgfcsdz'
		>>> create_config_json(values=values, config=DEFAULT_CONFIG)
		'/tmp/config.dkgfcsdz'
		"""
		fn = tempfile.mkstemp(prefix='config.', dir=self.tmpdir)[1]
		if not config:
			config = copy.copy(self.default_config)
		if values:
			for config_option, value in values.iteritems():
				config.update_entry(config_option, value)
		with open(fn, 'w') as fd:
			json.dump(config, fd)

		return fn

	def create_csv_file(self, person_list, mapping=None, fn_csv=None):
		"""
		Create CSV file for given persons
		>>> create_csv_file([Person('schoolA', 'student'), Person('schoolB', 'teacher')])
		'/tmp/import.sldfhgsg.csv'
		>>> create_csv_file([Person('schoolA', 'student'), Person('schoolB', 'teacher')], fn_csv='/tmp/import.foo.csv')
		'/tmp/import.foo.csv'
		>>> create_csv_file([Person('schoolA', 'student'), Person('schoolB', 'teacher')], headers={'firstname': 'Vorname', ...})
		'/tmp/import.cetjdfgj.csv'
		"""
		properties2headers = {v: k for k, v in self.default_config['csv']['mapping'].iteritems()}
		header2properties = self.default_config['csv']['mapping']
		if mapping:
			properties2headers = {v: k for k, v in mapping.iteritems()}
			header2properties = mapping
		header_row = header2properties.keys()
		random.shuffle(header_row)
		self.log.debug('Header row = %r', header_row)

		fn = fn_csv if fn_csv else tempfile.mkstemp(prefix='users.', dir=self.tmpdir)[1]
		writer = csv.DictWriter(
			open(fn, 'w'),
			header_row,
			restval='',
			delimiter=',',
			quotechar='"',
			quoting=csv.QUOTE_ALL)
		writer.writeheader()
		for person in person_list:
			person_dict = person.map_to_dict(properties2headers)
			self.log.debug('Person data = %r', person_dict)
			writer.writerow(person_dict)
		return fn

	def save_ldap_status(self):
		self.log.debug('Saving LDAP status...')
		self.ldap_status = set(self.lo.searchDn())
		self.log.debug('LDAP status saved.')

	def diff_ldap_status(self):
		self.log.debug('Reading LDAP status for check differences...')
		new_ldap_status = set(self.lo.searchDn())
		new_objects = new_ldap_status - self.ldap_status
		removed_objects = self.ldap_status - new_ldap_status
		self.log.debug('LDAP status diffed.')
		self.log.debug('New objects: %r', new_objects)
		self.log.debug('Removed objects: %r', removed_objects)
		return Bunch(new=new_objects, removed=removed_objects)

	def run_import(self, args, fail_on_error=True):
		cmd = ['/usr/share/ucs-school-import/scripts/ucs-school-user-import'] + args
		self.log.info('Starting import: %r', cmd)
		sys.stdout.flush()
		sys.stderr.flush()
		exitcode = subprocess.call(cmd)
		self.log.info('Import process exited with exit code %r', exitcode)
		if fail_on_error and exitcode:
			self.log.error('As requested raising an exception due to non-zero exit code')
			raise ImportException('Non-zero exit code %r' % (exitcode,))
		return exitcode


	def test_create_modify_delete_user(self):
		"""
		for role in ('student', 'teacher', 'staff', 'teacher_and_staff'):
			import user with role <role>
			modify user with role <role> → changing group memberships
			remove user with role <role>
		"""
		for role in ('student', 'teacher', 'staff', 'teacher_and_staff'):
			self.log.info('*** Importing a new single user with role %r', role)

			person = Person(self.ou_A.name, role)
			fn_csv = self.create_csv_file(person_list=[person])
			source_uid = 'sourceUID-%s' % (uts.random_string(),)
			record_uid = '%s;%s;%s' % (person.firstname, person.lastname, person.mail)
			config = {
				'sourceUID': source_uid,
				'input:filename': fn_csv,
				'user_role': role,
			}
			fn_config = self.create_config_json(values=config)
			# save ldap state for later comparison
			self.save_ldap_status()

			# start import
			self.run_import(['-c', fn_config])

			# check for new users in LDAP
			new_users = [x for x in self.diff_ldap_status().new if x.startswith('uid=')]
			if len(new_users) != 1:
				self.log.error('Invalid number of new users! Found new objects: %r', new_users)
				utils.fail('Stopping here')
			removed_users = [x for x in self.diff_ldap_status().removed if x.startswith('uid=')]
			if removed_users:
				self.log.error('Invalid number of removed users! Removed objects: %r', removed_users)
				utils.fail('Stopping here')

			# update dn+username of person and verify LDAP attributes
			person.update(dn=new_users[0], record_uid=record_uid, source_uid=source_uid)
			person.verify()


			self.log.info('*** Modifying a single user with role %r', role)

			if role == 'student':
				person.school_classes = {}
			if role in ('student', 'teacher', 'teacher_and_staff'):
				person.append_random_class()

			self.create_csv_file(person_list=[person], fn_csv=fn_csv)
			fn_config = self.create_config_json(values=config)
			# save ldap state for later comparison
			self.save_ldap_status()

			# start import
			self.run_import(['-c', fn_config])

			# check for new users in LDAP
			new_users = [x for x in self.diff_ldap_status().new if x.startswith('uid=')]
			if new_users:
				self.log.error('Invalid number of new users! Found new objects: %r', new_users)
				utils.fail('Stopping here')
			removed_users = [x for x in self.diff_ldap_status().removed if x.startswith('uid=')]
			if removed_users:
				self.log.error('Invalid number of removed users! Removed objects: %r', removed_users)
				utils.fail('Stopping here')

			# verify LDAP attributes
			person.verify()

			self.log.info('*** Remove a single user with role %r', role)

			# mark person as removed
			person.set_mode_to_delete()
			self.create_csv_file(person_list=[], fn_csv=fn_csv)
			fn_config = self.create_config_json(values=config)
			# save ldap state for later comparison
			self.save_ldap_status()

			# start import
			self.run_import(['-c', fn_config])

			# check for new users in LDAP
			new_users = [x for x in self.diff_ldap_status().new if x.startswith('uid=')]
			if new_users:
				self.log.error('Invalid number of new users! Found new objects: %r', new_users)
				utils.fail('Stopping here')
			removed_users = [x for x in self.diff_ldap_status().removed if x.startswith('uid=')]
			if len(removed_users) != 1:
				self.log.error('Invalid number of removed users! Removed objects: %r', removed_users)
				utils.fail('Stopping here')

			# verify LDAP attributes
			person.verify()

		self.log.info('Creating, modifying, removing user with role %r was successful', role)



	def test_create_modify_delete_user_with_username_and_recordUID_and_UDM_property(self):
		"""
		for role in ('student', 'teacher', 'staff', 'teacher_and_staff'):
			import user with role <role> and given username
			remove user with role <role> and given username
		"""
		for role in ('student', 'teacher', 'staff', 'teacher_and_staff'):
			hooks = PyHooks()
			hooks.create_hooks()
			try:
				self.log.info('*** Importing a new single user with role %r and username and recordUID', role)

				source_uid = 'sourceUID-%s' % (uts.random_string(),)
				record_uid_A = uts.random_name()
				record_uid_B = uts.random_name()

				config = copy.copy(self.default_config)
				config.update_entry('sourceUID', source_uid)
				config.update_entry('csv:mapping:Benutzername', 'username')
				config.update_entry('csv:mapping:DBID', 'record_uid')
				config.update_entry('scheme:recordUID', '<record_uid>')
				config.update_entry('user_role', role)

				person_list = [Person(self.ou_A.name, role), Person(self.ou_A.name, role)]
				person_list[0].update(record_uid=record_uid_A, source_uid=source_uid, description=uts.random_name())
				person_list[1].update(record_uid=record_uid_B, source_uid=source_uid, description=uts.random_name())
				fn_csv = self.create_csv_file(person_list=person_list, mapping=config['csv']['mapping'])
				config.update_entry('input:filename', fn_csv)
				fn_config = self.create_config_json(config=config)
				# save ldap state for later comparison
				self.save_ldap_status()

				# start import
				self.run_import(['-c', fn_config, '-i', fn_csv])

				# check for new users in LDAP
				new_users = [x for x in self.diff_ldap_status().new if x.startswith('uid=')]
				if len(new_users) != 2:
					self.log.error('Invalid number of new users! Found new objects: %r', new_users)
					utils.fail('Stopping here')
				removed_users = [x for x in self.diff_ldap_status().removed if x.startswith('uid=')]
				if removed_users:
					self.log.error('Invalid number of removed users! Removed objects: %r', removed_users)
					utils.fail('Stopping here')

				# update dn+username of person and verify LDAP attributes
				for person in person_list:
					person.verify()
				utils.verify_ldap_object(person.dn, expected_attr={'o': [',pre-create,post-create']}, strict=True, should_exist=True)

				def assert_and_print(exists, fn):
					status = os.path.exists(os.path.join(hooks.tmpdir, fn))
					self.log.debug('Hook touch file %r exists = %r' % (fn, status))
					assert exists == status, 'Unexpected status of hook touch file: exists=%s  expected=%s' % (status, exists)

				for fn in ('pre-create', 'post-create'):
					assert_and_print(True, fn)
				for fn in ('pre-modify', 'post-modify', 'pre-remove', 'post-remove'):
					assert_and_print(False, fn)

				self.log.info('*** Modifying a single user with role %r and username and recordUID', role)

				person_list[0].firstname = uts.random_name()
				person_list[1].lastname = uts.random_name()
				self.create_csv_file(person_list=person_list, fn_csv=fn_csv)
				fn_config = self.create_config_json(values=config)
				# save ldap state for later comparison
				self.save_ldap_status()
				# start import
				self.run_import(['-c', fn_config, '-i', fn_csv])
				# check for new users in LDAP
				new_users = [x for x in self.diff_ldap_status().new if x.startswith('uid=')]
				if new_users:
					self.log.error('Invalid number of new users! Found new objects: %r', new_users)
					utils.fail('Stopping here')
				removed_users = [x for x in self.diff_ldap_status().removed if x.startswith('uid=')]
				if removed_users:
					self.log.error('Invalid number of removed users! Removed objects: %r', removed_users)
					utils.fail('Stopping here')

				# verify LDAP attributes
				for person in person_list:
					person.verify()
				utils.verify_ldap_object(person.dn, expected_attr={'o': [',pre-create,post-create,pre-modify,post-modify']}, strict=True, should_exist=True)
				for fn in ('pre-create', 'post-create', 'pre-modify', 'post-modify'):
					assert_and_print(True, fn)
				for fn in ('pre-remove', 'post-remove'):
					assert_and_print(False, fn)


				self.log.info('*** Remove a single user with role %r and username and recordUID', role)

				# mark first person as removed
				person_list[0].set_mode_to_delete()
				self.create_csv_file(person_list=[person_list[1]], fn_csv=fn_csv)
				fn_config = self.create_config_json(values=config)
				# save ldap state for later comparison
				self.save_ldap_status()

				# start import
				self.run_import(['-c', fn_config, '-i', fn_csv])

				# check for new users in LDAP
				new_users = [x for x in self.diff_ldap_status().new if x.startswith('uid=')]
				if new_users:
					self.log.error('Invalid number of new users! Found new objects: %r', new_users)
					utils.fail('Stopping here')
				removed_users = [x for x in self.diff_ldap_status().removed if x.startswith('uid=')]
				if len(removed_users) != 1:
					self.log.error('Invalid number of removed users! Removed objects: %r', removed_users)
					utils.fail('Stopping here')

				# verify LDAP attributes
				for person in person_list:
					person.verify()
				for fn in ('pre-create', 'post-create', 'pre-modify', 'post-modify', 'pre-remove', 'post-remove'):
					assert_and_print(True, fn)

			finally:
				hooks.cleanup()
		self.log.info('Creating, modifying, removing user with role %r and username/recordUID was successful', role)


	def test_create_with_username_scheme(self):
		"""
		for role in ('student', 'teacher', 'staff', 'teacher_and_staff'):
			import user with role <role> and special username scheme
		"""
		for role in ('student', 'teacher', 'staff', 'teacher_and_staff'):
			self.log.info('*** Importing a new single user with role %r and username and recordUID', role)

			source_uid = 'sourceUID-%s' % (uts.random_string(),)
			record_uid = uts.random_name()

			config = copy.copy(self.default_config)
			config.update_entry('sourceUID', source_uid)
			config.update_entry('csv:mapping:DBID', 'record_uid')
			config.update_entry('scheme:recordUID', '<record_uid>')
			config.update_entry('user_role', role)
			config.update_entry('scheme:username:default', "<:umlauts>user-<firstname>[0:2].<lastname>[0:2][ALWAYSCOUNTER]")

			person = Person(self.ou_A.name, role)
			person.update(record_uid=record_uid, source_uid=source_uid, username=None)
			fn_csv = self.create_csv_file(person_list=[person], mapping=config['csv']['mapping'])
			config.update_entry('input:filename', fn_csv)
			fn_config = self.create_config_json(config=config)
			# save ldap state for later comparison
			self.save_ldap_status()

			# start import
			self.run_import(['-c', fn_config, '-i', fn_csv])

			# check for new users in LDAP
			new_users = [x for x in self.diff_ldap_status().new if x.startswith('uid=')]
			if len(new_users) != 1:
				self.log.error('Invalid number of new users! Found new objects: %r', new_users)
				utils.fail('Stopping here')
			removed_users = [x for x in self.diff_ldap_status().removed if x.startswith('uid=')]
			if removed_users:
				self.log.error('Invalid number of removed users! Removed objects: %r', removed_users)
				utils.fail('Stopping here')

			# update dn+username of person and verify LDAP attributes
			person.update(dn=new_users[0], record_uid=record_uid, source_uid=source_uid)
			person.verify()

			username_prefix = 'user-%s.%s' % (person.firstname[0:2], person.lastname[0:2])
			if person.username.rstrip('0123456789') != username_prefix:
				utils.fail('username %r does not start with expected string %r' % (person.username, username_prefix))
			self.log.info('Username %r starts as expected with string %r' % (person.username, username_prefix))

			# check if username history object exists
			self.log.info('Checking for unique-usernames object...')
			dn = 'cn=%s,cn=unique-usernames,cn=ucsschool,cn=univention,%s' % (username_prefix, self.lo.base)
			attrs = {
				'objectClass': ['ucsschoolUsername'],
				'ucsschoolUsernameNextNumber': ['2'],
				'cn': [username_prefix],
			}
			utils.verify_ldap_object(dn, expected_attr=attrs, strict=True, should_exist=True)
			self.log.debug('User object %r:\n%s', dn, pprint.PrettyPrinter(indent=2).pformat(self.lo.get(dn)))
			self.log.info('unique-usernames object has been found.')

	def test_create_modify_only(self):
		"""
		check if the --no-delete option works as expected
		"""
		for role in ('student', 'teacher', 'staff', 'teacher_and_staff'):
			self.log.info('*** Add/modify without delete with role %r', role)

			source_uid = 'sourceUID-%s' % (uts.random_string(),)
			config = copy.copy(self.default_config)
			config.update_entry('csv:mapping:Benutzername', 'username')
			config.update_entry('scheme:recordUID', '<username>')
			config.update_entry('sourceUID', source_uid)
			config.update_entry('user_role', role)
			personA = Person(self.ou_A.name, role)
			personB = Person(self.ou_A.name, role)

			self.log.info('Adding user A %r with role %r', personA.username, role)
			fn_csv = self.create_csv_file(person_list=[personA])
			fn_config = self.create_config_json(values=config)
			# start import
			self.run_import(['-c', fn_config, '-i', fn_csv, '--no-delete'])

			userlist = self.lo.searchDn('uid=%s' % (personA.username,))
			if len(userlist) != 1:
				self.log.error('Invalid number of users for personA! Found new objects: %r', userlist)
				utils.fail('Stopping here')
			personA.verify()

			self.log.info('Adding user B %r with role %r', personB.username, role)
			fn_csv = self.create_csv_file(person_list=[personB])
			fn_config = self.create_config_json(values=config)
			self.run_import(['-c', fn_config, '-i', fn_csv, '--no-delete'])

			for username in (personA.username, personB.username):
				userlist = self.lo.searchDn('uid=%s' % (username,))
				if len(userlist) != 1:
					self.log.error('Invalid number of user objects for user %r! Found new objects: %r', username, userlist)
					utils.fail('Stopping here')
			personA.verify()
			personB.verify()

			self.log.info('Modifying user A %r with role %r', personA.username, role)
			personA.lastname = uts.random_name()
			config.update_entry('no_delete', 'True')
			fn_csv = self.create_csv_file(person_list=[personA])
			fn_config = self.create_config_json(values=config)
			self.run_import(['-c', fn_config, '-i', fn_csv])  #  '--no-delete'  is not specified on purpose -> using config option "no_delete"

			for username in (personA.username, personB.username):
				userlist = self.lo.searchDn('uid=%s' % (username,))
				if len(userlist) != 1:
					self.log.error('Invalid number of user objects for user %r! Found new objects: %r', username, userlist)
					utils.fail('Stopping here')
			personA.verify()
			personB.verify()

	def test_create_with_attribute_schemes(self):
		"""
		Create a new user for each role:
		- use UDM template syntax (http://docs.software-univention.de/handbuch-4.1.html#users:templates)
          to define several custom values
        - employeeNumber is filled with a string consisting of first and last name and description
        - mailPrimaryAddress is also built from those attributes
		"""
		for role in ('student', 'teacher', 'staff', 'teacher_and_staff'):
			self.log.info('*** Importing a new single user with role %r from templates', role)

			source_uid = 'sourceUID-%s' % (uts.random_string(),)
			record_uid = uts.random_name()

			config = copy.copy(self.default_config)
			config.update_entry('sourceUID', source_uid)
			config.update_entry('csv:mapping:employeeNumber', 'employeeNumber')
			config.update_entry('csv:mapping:DBID', 'record_uid')
			config.update_entry('scheme:recordUID', '<record_uid>')
			config.update_entry('user_role', role)
			config.update_entry('scheme:username:default', "<:umlauts>user-<firstname>[0:2].<lastname>[0:2][ALWAYSCOUNTER]")
			config.update_entry('scheme:email', "<:umlauts><firstname:lower>[0:3].<lastname:lower>[2:5]@example.com")
			config.update_entry('scheme:employeeNumber', "The user's name is <firstname:upper> <lastname> <description>")

			person = Person(self.ou_A.name, role)
			person.update(record_uid=record_uid, source_uid=source_uid, username=None, mail=None, description=uts.random_name())
			fn_csv = self.create_csv_file(person_list=[person], mapping=config['csv']['mapping'])
			fn_config = self.create_config_json(config=config)
			# save ldap state for later comparison
			self.save_ldap_status()

			# start import
			self.run_import(['-c', fn_config, '-i', fn_csv])

			# check for new users in LDAP
			new_users = [x for x in self.diff_ldap_status().new if x.startswith('uid=')]
			if len(new_users) != 1:
				self.log.error('Invalid number of new users! Found new objects: %r', new_users)
				utils.fail('Stopping here')

			# update dn+username of person and verify LDAP attributes
			mail = '%s.%s@example.com' % (person.firstname[0:3].lower(), person.lastname[2:5].lower())
			person.update(dn=new_users[0], record_uid=record_uid, source_uid=source_uid, mail=mail)
			person.verify()

			username_prefix = 'user-%s.%s' % (person.firstname[0:2], person.lastname[0:2])
			if person.username.rstrip('0123456789') != username_prefix:
				utils.fail('username %r does not start with expected string %r' % (person.username, username_prefix))
			self.log.info('Username %r starts as expected with string %r' % (person.username, username_prefix))

			self.log.info('Testing mailPrimaryAddress and description...')
			values = {
				'employeeNumber': ["The user's name is %s %s %s" % (person.firstname.upper(), person.lastname, person.description)],
			}
			utils.verify_ldap_object(person.dn, expected_attr=values, strict=True, should_exist=True)
			self.log.debug('User object %r:\n%s', person.dn, pprint.PrettyPrinter(indent=2).pformat(self.lo.get(person.dn)))
			self.log.info('Test was successful.')

	def test_multivalue_attributes(self):
		"""
		Create/modify a new user for each role:
        - mailAlternativeAddress is filled with multiple strings
		"""
		for role in ('student', 'teacher', 'staff', 'teacher_and_staff'):
			self.log.info('*** Importing a new single user with role %r with multivalue attributes', role)

			source_uid = 'sourceUID-%s' % (uts.random_string(),)

			config = copy.copy(self.default_config)
			config.update_entry('sourceUID', source_uid)
			config.update_entry('csv:incell-delimiter:default', ';')
			config.update_entry('csv:mapping:Benutzername', 'username')
			config.update_entry('csv:mapping:recordUID', 'record_uid')
			config.update_entry('csv:mapping:mailAlternativeAddress', 'mailAlternativeAddress')
			config.update_entry('scheme:recordUID', '<username>')
			config.update_entry('sourceUID', source_uid)
			config.update_entry('user_role', role)

			class MultiPerson(Person):
				def __init__(self, school, role):
					Person.__init__(self, school, role)
					self.mailAlternativeAddress = '%s@example.com;%s@example.com;%s@example.com' % (uts.random_name(), uts.random_name(), uts.random_name())

				def map_to_dict(self, value_map):
					result = Person.map_to_dict(self, value_map)
					result[value_map.get('mailAlternativeAddress', '__EMPTY__')] = self.mailAlternativeAddress
					return result

				def expected_attributes(self):
					result = Person.expected_attributes(self)
					result['mailAlternativeAddress'] = self.mailAlternativeAddress.split(',')


			# create person with 3 alternative mail addresses
			person = MultiPerson(self.ou_A.name, role)
			person.update(record_uid=person.username, source_uid=source_uid)
			fn_csv = self.create_csv_file(person_list=[person], mapping=config['csv']['mapping'])
			fn_config = self.create_config_json(config=config)
			# start import
			self.run_import(['-c', fn_config, '-i', fn_csv])

			self.log.debug('User object %r:\n%s', person.dn, pprint.PrettyPrinter(indent=2).pformat(self.lo.get(person.dn)))
			person.verify()

			# modify person and set 1 alternative mail address
			person.update(mailAlternativeAddress='%s@example.com' % (uts.random_name(),))
			fn_csv = self.create_csv_file(person_list=[person], mapping=config['csv']['mapping'])
			fn_config = self.create_config_json(config=config)
			# start import
			self.run_import(['-c', fn_config, '-i', fn_csv])

			self.log.debug('User object %r:\n%s', person.dn, pprint.PrettyPrinter(indent=2).pformat(self.lo.get(person.dn)))
			person.verify()
			self.log.info('Test was successful.')

	def test_school_change(self):
		"""
		Create/modify a new user for each role:
        - mailAlternativeAddress is filled with multiple strings
		"""
		for role in ('student', 'teacher', 'staff', 'teacher_and_staff'):
			self.log.info('*** Importing a new single user with role %r and change school afterwards', role)

			source_uid = 'sourceUID-%s' % (uts.random_string(),)

			config = copy.copy(self.default_config)
			config.update_entry('sourceUID', source_uid)
			config.update_entry('csv:mapping:Benutzername', 'username')
			config.update_entry('csv:mapping:recordUID', 'record_uid')
			config.update_entry('scheme:recordUID', '<username>')
			config.update_entry('sourceUID', source_uid)
			config.update_entry('user_role', role)

			# create person in school A
			person = Person(self.ou_A.name, role)
			person.update(record_uid=person.username, source_uid=source_uid)
			fn_csv = self.create_csv_file(person_list=[person], mapping=config['csv']['mapping'])
			fn_config = self.create_config_json(config=config)
			# start import
			self.run_import(['-c', fn_config, '-i', fn_csv])

			self.log.debug('User object %r:\n%s', person.dn, pprint.PrettyPrinter(indent=2).pformat(self.lo.get(person.dn)))
			person.verify()

			# move person to school B
			person.update(school=self.ou_B.name)
			fn_csv = self.create_csv_file(person_list=[person], mapping=config['csv']['mapping'])
			fn_config = self.create_config_json(config=config)
			# start import
			self.run_import(['-c', fn_config, '-i', fn_csv])

			userlist = self.lo.searchDn('uid=%s' % (person.username,))
			if len(userlist) != 1:
				self.log.error('Invalid number of user objects for user %r! Found new objects: %r', person.username, userlist)
				utils.fail('Stopping here')

			person.update(dn=userlist[0])
			self.log.debug('User object %r:\n%s', person.dn, pprint.PrettyPrinter(indent=2).pformat(self.lo.get(person.dn)))
			person.verify()

			self.log.info('Test was successful.')


	def run(self):
		try:
			ucr = univention.testing.ucr.UCSTestConfigRegistry()
			ucr.load()

			with utu.UCSTestSchool() as schoolenv:
				self.ou_A.name, self.ou_A.dn = schoolenv.create_ou(name_edudc=ucr.get('hostname'))
				self.ou_B.name, self.ou_B.dn = schoolenv.create_ou(name_edudc=ucr.get('hostname'))
				self.lo = schoolenv.open_ldap_connection(admin=True)

				self.test_create_modify_delete_user()
				self.test_create_modify_delete_user_with_username_and_recordUID_and_UDM_property()
				self.test_create_with_username_scheme()
				self.test_create_modify_only()
				self.test_create_with_attribute_schemes()
				self.test_multivalue_attributes()
				self.test_school_change()
		finally:
			self.cleanup()

def main():
	logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format='%(levelname)s: %(funcName)s:%(lineno)d: %(message)s')
	tester = CLI_Import_v2_Tester()
	tester.run()


if __name__ == '__main__':
	main()
