#!/usr/share/ucs-test/runner python
## -*- coding: utf-8 -*-
## desc: Test moving a user from ou_A to ou_B (Bug #41609)
## tags: [apptest,ucsschool]
## roles: [domaincontroller_master]
## exposure: dangerous
## packages:
##   - ucs-school-import
## bugs: [41609]

import copy
import pprint
import univention.testing.strings as uts
from essential.importusers_cli_v2 import CLI_Import_v2_Tester
from essential.importusers import Person


class Test(CLI_Import_v2_Tester):
	def __init__(self):
		super(Test, self).__init__()
		self.ou_C = None

	def test(self):  # formally test_school_change()
		"""
		Test moving a user from ou_A to ou_B (Bug #41609).
		"""
		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.deepcopy(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, school_classes={})
			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, schools=[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)
				self.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()


def main():
	tester = Test()
	try:
		tester.run()
	finally:
		tester.cleanup()


if __name__ == '__main__':
	main()

