basic_test.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. # --- BEGIN COPYRIGHT BLOCK ---
  2. # Copyright (C) 2015 Red Hat, Inc.
  3. # All rights reserved.
  4. #
  5. # License: GPL (version 3 or any later version).
  6. # See LICENSE for details.
  7. # --- END COPYRIGHT BLOCK ---
  8. #
  9. import os
  10. import sys
  11. import time
  12. import ldap
  13. import ldap.sasl
  14. import logging
  15. import pytest
  16. import shutil
  17. from subprocess import check_output
  18. from lib389 import DirSrv, Entry, tools, tasks
  19. from lib389.tools import DirSrvTools
  20. from lib389._constants import *
  21. from lib389.properties import *
  22. from lib389.tasks import *
  23. from lib389.utils import *
  24. log = logging.getLogger(__name__)
  25. # Globals
  26. USER1_DN = 'uid=user1,' + DEFAULT_SUFFIX
  27. USER2_DN = 'uid=user2,' + DEFAULT_SUFFIX
  28. USER3_DN = 'uid=user3,' + DEFAULT_SUFFIX
  29. ROOTDSE_DEF_ATTR_LIST = ('namingContexts',
  30. 'supportedLDAPVersion',
  31. 'supportedControl',
  32. 'supportedExtension',
  33. 'supportedSASLMechanisms',
  34. 'vendorName',
  35. 'vendorVersion')
  36. class TopologyStandalone(object):
  37. def __init__(self, standalone):
  38. standalone.open()
  39. self.standalone = standalone
  40. @pytest.fixture(scope="module")
  41. def topology(request):
  42. """This fixture is used to standalone topology for the 'module'."""
  43. standalone = DirSrv(verbose=False)
  44. # Args for the standalone instance
  45. args_instance[SER_HOST] = HOST_STANDALONE
  46. args_instance[SER_PORT] = PORT_STANDALONE
  47. args_instance[SER_SERVERID_PROP] = SERVERID_STANDALONE
  48. args_standalone = args_instance.copy()
  49. standalone.allocate(args_standalone)
  50. # Get the status of the instance and restart it if it exists
  51. instance_standalone = standalone.exists()
  52. # Remove the instance
  53. if instance_standalone:
  54. standalone.delete()
  55. # Create the instance
  56. standalone.create()
  57. # Used to retrieve configuration information (dbdir, confdir...)
  58. standalone.open()
  59. # Delete each instance in the end
  60. def fin():
  61. standalone.delete()
  62. request.addfinalizer(fin)
  63. # Here we have standalone instance up and running
  64. return TopologyStandalone(standalone)
  65. @pytest.fixture(scope="module")
  66. def import_example_ldif(topology):
  67. """Import the Example LDIF for the tests in this suite"""
  68. log.info('Initializing the "basic" test suite')
  69. ldif = '%s/Example.ldif' % get_data_dir(topology.standalone.prefix)
  70. import_ldif = topology.standalone.get_ldif_dir() + "/Example.ldif"
  71. shutil.copyfile(ldif, import_ldif)
  72. try:
  73. topology.standalone.tasks.importLDIF(suffix=DEFAULT_SUFFIX,
  74. input_file=import_ldif,
  75. args={TASK_WAIT: True})
  76. except ValueError:
  77. log.error('Online import failed')
  78. assert False
  79. @pytest.fixture(params=ROOTDSE_DEF_ATTR_LIST)
  80. def rootdse_attr(topology, request):
  81. """Adds an attr from the list
  82. as the default attr to the rootDSE
  83. """
  84. RETURN_DEFAULT_OPATTR = "nsslapd-return-default-opattr"
  85. rootdse_attr_name = request.param
  86. log.info(" Add the %s: %s to rootdse" % (RETURN_DEFAULT_OPATTR,
  87. rootdse_attr_name))
  88. mod = [(ldap.MOD_ADD, RETURN_DEFAULT_OPATTR, rootdse_attr_name)]
  89. try:
  90. topology.standalone.modify_s("", mod)
  91. except ldap.LDAPError as e:
  92. log.fatal('Failed to add attr: error (%s)' % (e.message['desc']))
  93. assert False
  94. def fin():
  95. log.info(" Delete the %s: %s from rootdse" % (RETURN_DEFAULT_OPATTR,
  96. rootdse_attr_name))
  97. mod = [(ldap.MOD_DELETE, RETURN_DEFAULT_OPATTR, rootdse_attr_name)]
  98. try:
  99. topology.standalone.modify_s("", mod)
  100. except ldap.LDAPError as e:
  101. log.fatal('Failed to delete attr: error (%s)' % (e.message['desc']))
  102. assert False
  103. request.addfinalizer(fin)
  104. return rootdse_attr_name
  105. def test_basic_ops(topology, import_example_ldif):
  106. """Test doing adds, mods, modrdns, and deletes"""
  107. log.info('Running test_basic_ops...')
  108. USER1_NEWDN = 'cn=user1'
  109. USER2_NEWDN = 'cn=user2'
  110. USER3_NEWDN = 'cn=user3'
  111. NEW_SUPERIOR = 'ou=people,' + DEFAULT_SUFFIX
  112. USER1_RDN_DN = 'cn=user1,' + DEFAULT_SUFFIX
  113. USER2_RDN_DN = 'cn=user2,' + DEFAULT_SUFFIX
  114. USER3_RDN_DN = 'cn=user3,' + NEW_SUPERIOR # New superior test
  115. #
  116. # Adds
  117. #
  118. try:
  119. topology.standalone.add_s(Entry((USER1_DN,
  120. {'objectclass': "top extensibleObject".split(),
  121. 'sn': '1',
  122. 'cn': 'user1',
  123. 'uid': 'user1',
  124. 'userpassword': 'password'})))
  125. except ldap.LDAPError as e:
  126. log.error('Failed to add test user' + USER1_DN + ': error ' + e.message['desc'])
  127. assert False
  128. try:
  129. topology.standalone.add_s(Entry((USER2_DN,
  130. {'objectclass': "top extensibleObject".split(),
  131. 'sn': '2',
  132. 'cn': 'user2',
  133. 'uid': 'user2',
  134. 'userpassword': 'password'})))
  135. except ldap.LDAPError as e:
  136. log.error('Failed to add test user' + USER2_DN + ': error ' + e.message['desc'])
  137. assert False
  138. try:
  139. topology.standalone.add_s(Entry((USER3_DN,
  140. {'objectclass': "top extensibleObject".split(),
  141. 'sn': '3',
  142. 'cn': 'user3',
  143. 'uid': 'user3',
  144. 'userpassword': 'password'})))
  145. except ldap.LDAPError as e:
  146. log.error('Failed to add test user' + USER3_DN + ': error ' + e.message['desc'])
  147. assert False
  148. #
  149. # Mods
  150. #
  151. try:
  152. topology.standalone.modify_s(USER1_DN, [(ldap.MOD_ADD, 'description',
  153. 'New description')])
  154. except ldap.LDAPError as e:
  155. log.error('Failed to add description: error ' + e.message['desc'])
  156. assert False
  157. try:
  158. topology.standalone.modify_s(USER1_DN, [(ldap.MOD_REPLACE, 'description',
  159. 'Modified description')])
  160. except ldap.LDAPError as e:
  161. log.error('Failed to modify description: error ' + e.message['desc'])
  162. assert False
  163. try:
  164. topology.standalone.modify_s(USER1_DN, [(ldap.MOD_DELETE, 'description',
  165. None)])
  166. except ldap.LDAPError as e:
  167. log.error('Failed to delete description: error ' + e.message['desc'])
  168. assert False
  169. #
  170. # Modrdns
  171. #
  172. try:
  173. topology.standalone.rename_s(USER1_DN, USER1_NEWDN, delold=1)
  174. except ldap.LDAPError as e:
  175. log.error('Failed to modrdn user1: error ' + e.message['desc'])
  176. assert False
  177. try:
  178. topology.standalone.rename_s(USER2_DN, USER2_NEWDN, delold=0)
  179. except ldap.LDAPError as e:
  180. log.error('Failed to modrdn user2: error ' + e.message['desc'])
  181. assert False
  182. # Modrdn - New superior
  183. try:
  184. topology.standalone.rename_s(USER3_DN, USER3_NEWDN,
  185. newsuperior=NEW_SUPERIOR, delold=1)
  186. except ldap.LDAPError as e:
  187. log.error('Failed to modrdn(new superior) user3: error ' + e.message['desc'])
  188. assert False
  189. #
  190. # Deletes
  191. #
  192. try:
  193. topology.standalone.delete_s(USER1_RDN_DN)
  194. except ldap.LDAPError as e:
  195. log.error('Failed to delete test entry1: ' + e.message['desc'])
  196. assert False
  197. try:
  198. topology.standalone.delete_s(USER2_RDN_DN)
  199. except ldap.LDAPError as e:
  200. log.error('Failed to delete test entry2: ' + e.message['desc'])
  201. assert False
  202. try:
  203. topology.standalone.delete_s(USER3_RDN_DN)
  204. except ldap.LDAPError as e:
  205. log.error('Failed to delete test entry3: ' + e.message['desc'])
  206. assert False
  207. log.info('test_basic_ops: PASSED')
  208. def test_basic_import_export(topology, import_example_ldif):
  209. """Test online and offline LDIF imports & exports"""
  210. log.info('Running test_basic_import_export...')
  211. tmp_dir = '/tmp'
  212. #
  213. # Test online/offline LDIF imports
  214. #
  215. # Generate a test ldif (50k entries)
  216. ldif_dir = topology.standalone.get_ldif_dir()
  217. import_ldif = ldif_dir + '/basic_import.ldif'
  218. try:
  219. topology.standalone.buildLDIF(50000, import_ldif)
  220. except OSError as e:
  221. log.fatal('test_basic_import_export: failed to create test ldif,\
  222. error: %s - %s' % (e.errno, e.strerror))
  223. assert False
  224. # Online
  225. try:
  226. topology.standalone.tasks.importLDIF(suffix=DEFAULT_SUFFIX,
  227. input_file=import_ldif,
  228. args={TASK_WAIT: True})
  229. except ValueError:
  230. log.fatal('test_basic_import_export: Online import failed')
  231. assert False
  232. # Offline
  233. if not topology.standalone.ldif2db(DEFAULT_BENAME, None, None, None, import_ldif):
  234. log.fatal('test_basic_import_export: Offline import failed')
  235. assert False
  236. #
  237. # Test online and offline LDIF export
  238. #
  239. # Online export
  240. export_ldif = ldif_dir + '/export.ldif'
  241. exportTask = Tasks(topology.standalone)
  242. try:
  243. args = {TASK_WAIT: True}
  244. exportTask.exportLDIF(DEFAULT_SUFFIX, None, export_ldif, args)
  245. except ValueError:
  246. log.fatal('test_basic_import_export: Online export failed')
  247. assert False
  248. # Offline export
  249. if not topology.standalone.db2ldif(DEFAULT_BENAME, (DEFAULT_SUFFIX,),
  250. None, None, None, export_ldif):
  251. log.fatal('test_basic_import_export: Failed to run offline db2ldif')
  252. assert False
  253. #
  254. # Cleanup - Import the Example LDIF for the other tests in this suite
  255. #
  256. ldif = '%s/Example.ldif' % get_data_dir(topology.standalone.prefix)
  257. import_ldif = topology.standalone.get_ldif_dir() + "/Example.ldif"
  258. shutil.copyfile(ldif, import_ldif)
  259. try:
  260. topology.standalone.tasks.importLDIF(suffix=DEFAULT_SUFFIX,
  261. input_file=import_ldif,
  262. args={TASK_WAIT: True})
  263. except ValueError:
  264. log.fatal('test_basic_import_export: Online import failed')
  265. assert False
  266. log.info('test_basic_import_export: PASSED')
  267. def test_basic_backup(topology, import_example_ldif):
  268. """Test online and offline back and restore"""
  269. log.info('Running test_basic_backup...')
  270. backup_dir = topology.standalone.get_bak_dir() + '/backup_test'
  271. # Test online backup
  272. try:
  273. topology.standalone.tasks.db2bak(backup_dir=backup_dir,
  274. args={TASK_WAIT: True})
  275. except ValueError:
  276. log.fatal('test_basic_backup: Online backup failed')
  277. assert False
  278. # Test online restore
  279. try:
  280. topology.standalone.tasks.bak2db(backup_dir=backup_dir,
  281. args={TASK_WAIT: True})
  282. except ValueError:
  283. log.fatal('test_basic_backup: Online restore failed')
  284. assert False
  285. # Test offline backup
  286. if not topology.standalone.db2bak(backup_dir):
  287. log.fatal('test_basic_backup: Offline backup failed')
  288. assert False
  289. # Test offline restore
  290. if not topology.standalone.bak2db(backup_dir):
  291. log.fatal('test_basic_backup: Offline backup failed')
  292. assert False
  293. log.info('test_basic_backup: PASSED')
  294. def test_basic_acl(topology, import_example_ldif):
  295. """Run some basic access control(ACL) tests"""
  296. log.info('Running test_basic_acl...')
  297. DENY_ACI = ('(targetattr = "*") (version 3.0;acl "deny user";deny (all)' +
  298. '(userdn = "ldap:///' + USER1_DN + '");)')
  299. #
  300. # Add two users
  301. #
  302. try:
  303. topology.standalone.add_s(Entry((USER1_DN,
  304. {'objectclass': "top extensibleObject".split(),
  305. 'sn': '1',
  306. 'cn': 'user 1',
  307. 'uid': 'user1',
  308. 'userpassword': PASSWORD})))
  309. except ldap.LDAPError as e:
  310. log.fatal('test_basic_acl: Failed to add test user ' + USER1_DN
  311. + ': error ' + e.message['desc'])
  312. assert False
  313. try:
  314. topology.standalone.add_s(Entry((USER2_DN,
  315. {'objectclass': "top extensibleObject".split(),
  316. 'sn': '2',
  317. 'cn': 'user 2',
  318. 'uid': 'user2',
  319. 'userpassword': PASSWORD})))
  320. except ldap.LDAPError as e:
  321. log.fatal('test_basic_acl: Failed to add test user ' + USER1_DN
  322. + ': error ' + e.message['desc'])
  323. assert False
  324. #
  325. # Add an aci that denies USER1 from doing anything,
  326. # and also set the default anonymous access
  327. #
  328. try:
  329. topology.standalone.modify_s(DEFAULT_SUFFIX, [(ldap.MOD_ADD, 'aci', DENY_ACI)])
  330. except ldap.LDAPError as e:
  331. log.fatal('test_basic_acl: Failed to add DENY ACI: error ' + e.message['desc'])
  332. assert False
  333. #
  334. # Make sure USER1_DN can not search anything, but USER2_dn can...
  335. #
  336. try:
  337. topology.standalone.simple_bind_s(USER1_DN, PASSWORD)
  338. except ldap.LDAPError as e:
  339. log.fatal('test_basic_acl: Failed to bind as user1, error: ' + e.message['desc'])
  340. assert False
  341. try:
  342. entries = topology.standalone.search_s(DEFAULT_SUFFIX,
  343. ldap.SCOPE_SUBTREE,
  344. '(uid=*)')
  345. if entries:
  346. log.fatal('test_basic_acl: User1 was incorrectly able to search the suffix!')
  347. assert False
  348. except ldap.LDAPError as e:
  349. log.fatal('test_basic_acl: Search suffix failed(as user1): ' + e.message['desc'])
  350. assert False
  351. # Now try user2... Also check that userpassword is stripped out
  352. try:
  353. topology.standalone.simple_bind_s(USER2_DN, PASSWORD)
  354. except ldap.LDAPError as e:
  355. log.fatal('test_basic_acl: Failed to bind as user2, error: ' + e.message['desc'])
  356. assert False
  357. try:
  358. entries = topology.standalone.search_s(DEFAULT_SUFFIX,
  359. ldap.SCOPE_SUBTREE,
  360. '(uid=user1)')
  361. if not entries:
  362. log.fatal('test_basic_acl: User1 incorrectly not able to search the suffix')
  363. assert False
  364. if entries[0].hasAttr('userpassword'):
  365. # The default anonymous access aci should have stripped out userpassword
  366. log.fatal('test_basic_acl: User2 was incorrectly able to see userpassword')
  367. assert False
  368. except ldap.LDAPError as e:
  369. log.fatal('test_basic_acl: Search for user1 failed(as user2): ' + e.message['desc'])
  370. assert False
  371. # Make sure Root DN can also search (this also resets the bind dn to the
  372. # Root DN for future operations)
  373. try:
  374. topology.standalone.simple_bind_s(DN_DM, PW_DM)
  375. except ldap.LDAPError as e:
  376. log.fatal('test_basic_acl: Failed to bind as ROotDN, error: ' + e.message['desc'])
  377. assert False
  378. try:
  379. entries = topology.standalone.search_s(DEFAULT_SUFFIX,
  380. ldap.SCOPE_SUBTREE,
  381. '(uid=*)')
  382. if not entries:
  383. log.fatal('test_basic_acl: Root DN incorrectly not able to search the suffix')
  384. assert False
  385. except ldap.LDAPError as e:
  386. log.fatal('test_basic_acl: Search for user1 failed(as user2): ' + e.message['desc'])
  387. assert False
  388. #
  389. # Cleanup
  390. #
  391. try:
  392. topology.standalone.modify_s(DEFAULT_SUFFIX, [(ldap.MOD_DELETE, 'aci', DENY_ACI)])
  393. except ldap.LDAPError as e:
  394. log.fatal('test_basic_acl: Failed to delete DENY ACI: error ' + e.message['desc'])
  395. assert False
  396. try:
  397. topology.standalone.delete_s(USER1_DN)
  398. except ldap.LDAPError as e:
  399. log.fatal('test_basic_acl: Failed to delete test entry1: ' + e.message['desc'])
  400. assert False
  401. try:
  402. topology.standalone.delete_s(USER2_DN)
  403. except ldap.LDAPError as e:
  404. log.fatal('test_basic_acl: Failed to delete test entry2: ' + e.message['desc'])
  405. assert False
  406. log.info('test_basic_acl: PASSED')
  407. def test_basic_searches(topology, import_example_ldif):
  408. """The search results are gathered from testing with Example.ldif"""
  409. log.info('Running test_basic_searches...')
  410. filters = (('(uid=scarter)', 1),
  411. ('(uid=tmorris*)', 1),
  412. ('(uid=*hunt*)', 4),
  413. ('(uid=*cope)', 2),
  414. ('(mail=*)', 150),
  415. ('(roomnumber>=4000)', 35),
  416. ('(roomnumber<=4000)', 115),
  417. ('(&(roomnumber>=4000)(roomnumber<=4500))', 18),
  418. ('(!(l=sunnyvale))', 120),
  419. ('(&(uid=t*)(l=santa clara))', 7),
  420. ('(|(uid=k*)(uid=r*))', 18),
  421. ('(|(uid=t*)(l=sunnyvale))', 50),
  422. ('(&(!(uid=r*))(ou=people))', 139),
  423. ('(&(uid=m*)(l=sunnyvale)(ou=people)(mail=*example*)(roomNumber=*))', 3),
  424. ('(&(|(uid=m*)(l=santa clara))(roomNumber=22*))', 5),
  425. ('(&(|(uid=m*)(l=santa clara))(roomNumber=22*)(!(roomnumber=2254)))', 4))
  426. for (search_filter, search_result) in filters:
  427. try:
  428. entries = topology.standalone.search_s(DEFAULT_SUFFIX,
  429. ldap.SCOPE_SUBTREE,
  430. search_filter)
  431. if len(entries) != search_result:
  432. log.fatal('test_basic_searches: An incorrect number of entries\
  433. was returned from filter (%s): (%d) expected (%d)' %
  434. (search_filter, len(entries), search_result))
  435. assert False
  436. except ldap.LDAPError as e:
  437. log.fatal('Search failed: ' + e.message['desc'])
  438. assert False
  439. log.info('test_basic_searches: PASSED')
  440. def test_basic_referrals(topology, import_example_ldif):
  441. """Set the server to referral mode,
  442. and make sure we recive the referal error(10)
  443. """
  444. log.info('Running test_basic_referrals...')
  445. SUFFIX_CONFIG = 'cn="dc=example,dc=com",cn=mapping tree,cn=config'
  446. #
  447. # Set the referral, adn the backend state
  448. #
  449. try:
  450. topology.standalone.modify_s(SUFFIX_CONFIG,
  451. [(ldap.MOD_REPLACE,
  452. 'nsslapd-referral',
  453. 'ldap://localhost.localdomain:389/o%3dnetscaperoot')])
  454. except ldap.LDAPError as e:
  455. log.fatal('test_basic_referrals: Failed to set referral: error ' + e.message['desc'])
  456. assert False
  457. try:
  458. topology.standalone.modify_s(SUFFIX_CONFIG, [(ldap.MOD_REPLACE,
  459. 'nsslapd-state', 'Referral')])
  460. except ldap.LDAPError as e:
  461. log.fatal('test_basic_referrals: Failed to set backend state: error '
  462. + e.message['desc'])
  463. assert False
  464. #
  465. # Test that a referral error is returned
  466. #
  467. topology.standalone.set_option(ldap.OPT_REFERRALS, 0) # Do not follow referral
  468. try:
  469. topology.standalone.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, 'objectclass=top')
  470. except ldap.REFERRAL:
  471. pass
  472. except ldap.LDAPError as e:
  473. log.fatal('test_basic_referrals: Search failed: ' + e.message['desc'])
  474. assert False
  475. #
  476. # Make sure server can restart in referral mode
  477. #
  478. topology.standalone.restart(timeout=10)
  479. #
  480. # Cleanup
  481. #
  482. try:
  483. topology.standalone.modify_s(SUFFIX_CONFIG, [(ldap.MOD_REPLACE,
  484. 'nsslapd-state', 'Backend')])
  485. except ldap.LDAPError as e:
  486. log.fatal('test_basic_referrals: Failed to set backend state: error '
  487. + e.message['desc'])
  488. assert False
  489. try:
  490. topology.standalone.modify_s(SUFFIX_CONFIG, [(ldap.MOD_DELETE,
  491. 'nsslapd-referral', None)])
  492. except ldap.LDAPError as e:
  493. log.fatal('test_basic_referrals: Failed to delete referral: error '
  494. + e.message['desc'])
  495. assert False
  496. topology.standalone.set_option(ldap.OPT_REFERRALS, 1)
  497. log.info('test_basic_referrals: PASSED')
  498. def test_basic_systemctl(topology, import_example_ldif):
  499. """Test systemctl can stop and start the server. Also test that start reports an
  500. error when the instance does not start. Only for RPM builds
  501. """
  502. log.info('Running test_basic_systemctl...')
  503. # We can only use systemctl on RPM installations
  504. if topology.standalone.prefix and topology.standalone.prefix != '/':
  505. return
  506. data_dir = topology.standalone.getDir(__file__, DATA_DIR)
  507. tmp_dir = '/tmp'
  508. config_dir = topology.standalone.confdir
  509. start_ds = 'sudo systemctl start dirsrv@' + topology.standalone.serverid + '.service'
  510. stop_ds = 'sudo systemctl stop dirsrv@' + topology.standalone.serverid + '.service'
  511. is_running = 'sudo systemctl is-active dirsrv@' + topology.standalone.serverid + '.service'
  512. #
  513. # Stop the server
  514. #
  515. log.info('Stopping the server...')
  516. rc = os.system(stop_ds)
  517. log.info('Check the status...')
  518. if rc != 0 or os.system(is_running) == 0:
  519. log.fatal('test_basic_systemctl: Failed to stop the server')
  520. assert False
  521. log.info('Stopped the server.')
  522. #
  523. # Start the server
  524. #
  525. log.info('Starting the server...')
  526. rc = os.system(start_ds)
  527. log.info('Check the status...')
  528. if rc != 0 or os.system(is_running) != 0:
  529. log.fatal('test_basic_systemctl: Failed to start the server')
  530. assert False
  531. log.info('Started the server.')
  532. #
  533. # Stop the server, break the dse.ldif so a start fails,
  534. # and verify that systemctl detects the failed start
  535. #
  536. log.info('Stopping the server...')
  537. rc = os.system(stop_ds)
  538. log.info('Check the status...')
  539. if rc != 0 or os.system(is_running) == 0:
  540. log.fatal('test_basic_systemctl: Failed to stop the server')
  541. assert False
  542. log.info('Stopped the server before breaking the dse.ldif.')
  543. shutil.copy(config_dir + '/dse.ldif', tmp_dir)
  544. shutil.copy(data_dir + 'basic/dse.ldif.broken', config_dir + '/dse.ldif')
  545. log.info('Attempting to start the server with broken dse.ldif...')
  546. rc = os.system(start_ds)
  547. log.info('Check the status...')
  548. if rc == 0 or os.system(is_running) == 0:
  549. log.fatal('test_basic_systemctl: The server incorrectly started')
  550. assert False
  551. log.info('Server failed to start as expected')
  552. time.sleep(5)
  553. #
  554. # Fix the dse.ldif, and make sure the server starts up,
  555. # and systemctl correctly identifies the successful start
  556. #
  557. shutil.copy(tmp_dir + '/dse.ldif', config_dir)
  558. log.info('Starting the server with good dse.ldif...')
  559. rc = os.system(start_ds)
  560. time.sleep(5)
  561. log.info('Check the status...')
  562. if rc != 0 or os.system(is_running) != 0:
  563. log.fatal('test_basic_systemctl: Failed to start the server')
  564. assert False
  565. log.info('Server started after fixing dse.ldif.')
  566. time.sleep(1)
  567. log.info('test_basic_systemctl: PASSED')
  568. def test_basic_ldapagent(topology, import_example_ldif):
  569. """Test that the ldap agent starts"""
  570. log.info('Running test_basic_ldapagent...')
  571. var_dir = topology.standalone.get_local_state_dir()
  572. config_file = os.path.join(topology.standalone.get_sysconf_dir(), 'dirsrv/config/agent.conf')
  573. cmd = 'sudo %s %s' % (os.path.join(topology.standalone.get_sbin_dir(), 'ldap-agent'), config_file)
  574. agent_config_file = open(config_file, 'w')
  575. agent_config_file.write('agentx-master ' + var_dir + '/agentx/master\n')
  576. agent_config_file.write('agent-logdir ' + var_dir + '/log/dirsrv\n')
  577. agent_config_file.write('server slapd-' + topology.standalone.serverid + '\n')
  578. agent_config_file.close()
  579. rc = os.system(cmd)
  580. if rc != 0:
  581. log.fatal('test_basic_ldapagent: Failed to start snmp ldap agent %s: error %d' % (cmd, rc))
  582. assert False
  583. log.info('snmp ldap agent started')
  584. #
  585. # Cleanup - kill the agent
  586. #
  587. pid = check_output(['pidof', '-s', 'ldap-agent-bin'])
  588. log.info('Cleanup - killing agent: ' + pid)
  589. rc = os.system('sudo kill -9 ' + pid)
  590. log.info('test_basic_ldapagent: PASSED')
  591. def test_basic_dse(topology, import_example_ldif):
  592. """Test that the dse.ldif is not wipped out
  593. after the process is killed (bug 910581)
  594. """
  595. log.info('Running test_basic_dse...')
  596. dse_file = topology.standalone.confdir + '/dse.ldif'
  597. pid = check_output(['pidof', '-s', 'ns-slapd'])
  598. os.system('sudo kill -9 ' + pid)
  599. if os.path.getsize(dse_file) == 0:
  600. log.fatal('test_basic_dse: dse.ldif\'s content was incorrectly removed!')
  601. assert False
  602. topology.standalone.start(timeout=60)
  603. log.info('dse.ldif was not corrupted, and the server was restarted')
  604. log.info('test_basic_dse: PASSED')
  605. @pytest.mark.parametrize("rootdse_attr_name", ROOTDSE_DEF_ATTR_LIST)
  606. def test_def_rootdse_attr(topology, import_example_ldif, rootdse_attr_name):
  607. """Tests that operational attributes
  608. are not returned by default in rootDSE searches
  609. """
  610. log.info(" Assert rootdse search hasn't %s attr" % rootdse_attr_name)
  611. try:
  612. entries = topology.standalone.search_s("", ldap.SCOPE_BASE)
  613. entry = str(entries[0])
  614. assert rootdse_attr_name not in entry
  615. except ldap.LDAPError as e:
  616. log.fatal('Search failed, error: ' + e.message['desc'])
  617. assert False
  618. def test_mod_def_rootdse_attr(topology, import_example_ldif, rootdse_attr):
  619. """Tests that operational attributes are returned
  620. by default in rootDSE searches after config modification
  621. """
  622. log.info(" Assert rootdse search has %s attr" % rootdse_attr)
  623. try:
  624. entries = topology.standalone.search_s("", ldap.SCOPE_BASE)
  625. entry = str(entries[0])
  626. assert rootdse_attr in entry
  627. except ldap.LDAPError as e:
  628. log.fatal('Search failed, error: ' + e.message['desc'])
  629. assert False
  630. if __name__ == '__main__':
  631. # Run isolated
  632. # -s for DEBUG mode
  633. CURRENT_FILE = os.path.realpath(__file__)
  634. pytest.main("-s %s" % CURRENT_FILE)