create_test.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. #!/usr/bin/python3
  2. #
  3. # --- BEGIN COPYRIGHT BLOCK ---
  4. # Copyright (C) 2022 Red Hat, Inc.
  5. # All rights reserved.
  6. #
  7. # License: GPL (version 3 or any later version).
  8. # See LICENSE for details.
  9. # --- END COPYRIGHT BLOCK ---
  10. #
  11. # PYTHON_ARGCOMPLETE_OK
  12. import argparse, argcomplete
  13. import argcomplete
  14. import datetime
  15. import optparse
  16. import os
  17. import re
  18. import sys
  19. import uuid
  20. from lib389 import topologies
  21. """This script generates a template test script that handles the
  22. non-interesting parts of a test script:
  23. - topology fixture that doesn't exist in in lib389/topologies.py
  24. - test function (to be completed by the user),
  25. - run-isolated function
  26. """
  27. def display_usage():
  28. """Display the usage"""
  29. print('\nUsage:\ncreate_ticket.py -t|--ticket <ticket number> ' +
  30. '-s|--suite <suite name> ' +
  31. '[ i|--instances <number of standalone instances> ' +
  32. '[ -m|--suppliers <number of suppliers> -h|--hubs <number of hubs> ' +
  33. '-c|--consumers <number of consumers> ] -o|--outputfile -C|--copyright <name of the entity>]\n')
  34. print('If only "-t" is provided then a single standalone instance is ' +
  35. 'created. Or you can create a test suite script using ' +
  36. '"-s|--suite" instead of using "-t|--ticket". The "-i" option ' +
  37. 'can add multiple standalone instances (maximum 99). However, you' +
  38. ' can not mix "-i" with the replication options (-m, -h , -c). ' +
  39. 'There is a maximum of 99 suppliers, 99 hubs, and 99 consumers.')
  40. print('If "-s|--suite" option was chosen, then no topology would be added ' +
  41. 'to the test script. You can find predefined fixtures in the lib389/topologies.py ' +
  42. 'and use them or write a new one if you have a special case.')
  43. exit(1)
  44. def write_finalizer():
  45. """Write the finalizer function - delete/stop each instance"""
  46. def writeInstanceOp(action):
  47. TEST.write(' map(lambda inst: inst.{}(), topology.all_insts.values())\n'.format(action))
  48. TEST.write('\n def fin():\n')
  49. TEST.write(' """If we are debugging just stop the instances, otherwise remove them"""\n\n')
  50. TEST.write(' if DEBUGGING:\n')
  51. writeInstanceOp('stop')
  52. TEST.write(' else:\n')
  53. writeInstanceOp('delete')
  54. TEST.write('\n request.addfinalizer(fin)')
  55. TEST.write('\n\n')
  56. def get_existing_topologies(inst, suppliers, hubs, consumers):
  57. """Check if the requested topology exists"""
  58. setup_text = ""
  59. if inst:
  60. if inst == 1:
  61. i = 'st'
  62. setup_text = "Standalone Instance"
  63. else:
  64. i = 'i{}'.format(inst)
  65. setup_text = "{} Standalone Instances".format(inst)
  66. else:
  67. i = ''
  68. if suppliers:
  69. ms = 'm{}'.format(suppliers)
  70. if len(setup_text) > 0:
  71. setup_text += ", "
  72. if suppliers == 1:
  73. setup_text += "Supplier Instance"
  74. else:
  75. setup_text += "{} Supplier Instances".format(suppliers)
  76. else:
  77. ms = ''
  78. if hubs:
  79. hs = 'h{}'.format(hubs)
  80. if len(setup_text) > 0:
  81. setup_text += ", "
  82. if hubs == 1:
  83. setup_text += "Hub Instance"
  84. else:
  85. setup_text += "{} Hub Instances".format(hubs)
  86. else:
  87. hs = ''
  88. if consumers:
  89. cs = 'c{}'.format(consumers)
  90. if len(setup_text) > 0:
  91. setup_text += ", "
  92. if consumers == 1:
  93. setup_text += "Consumer Instance"
  94. else:
  95. setup_text += "{} Consumer Instances".format(consumers)
  96. else:
  97. cs = ''
  98. my_topology = 'topology_{}{}{}{}'.format(i, ms, hs, cs)
  99. # Returns True in the first element of a list, if topology was found
  100. if my_topology in dir(topologies):
  101. return [True, my_topology, setup_text]
  102. else:
  103. return [False, my_topology, setup_text]
  104. def check_id_uniqueness(id_value):
  105. """Checks if ID is already present in other tests.
  106. create_test.py script should exist in the directory
  107. with a 'tests' dir.
  108. """
  109. tests_dir = os.path.join(os.getcwd(), 'tests')
  110. for root, dirs, files in os.walk(tests_dir):
  111. for name in files:
  112. if name.endswith('.py'):
  113. with open(os.path.join(root, name), "r") as cifile:
  114. for line in cifile:
  115. if re.search(str(id_value), line):
  116. return False
  117. return True
  118. def display_uuid():
  119. tc_uuid = '0'
  120. while not check_id_uniqueness(tc_uuid): tc_uuid = uuid.uuid4()
  121. print(str(tc_uuid))
  122. exit(0)
  123. desc = 'Script to generate an initial lib389 test script. ' + \
  124. 'This generates the topology, test, final, and run-isolated functions.'
  125. if len(sys.argv) > 0:
  126. parser = argparse.ArgumentParser()
  127. parser.add_argument('-t', '--ticket', default=None,
  128. help="The name of the ticket/issue to include in the script name: 'ticket_<TEXT INPUT>_test.py'")
  129. parser.add_argument('-s', '--suite', default=None, help="Name for the test: '<TEXT INPUT>_test.py'")
  130. parser.add_argument('-i', '--instances', default='0', help="Number of instances needed in the test")
  131. parser.add_argument('-m', '--suppliers', default='0',
  132. help="Number of replication suppliers needed in the test")
  133. parser.add_argument('-b', '--hubs', default='0', help="Number of replication hubs needed in the test")
  134. parser.add_argument('-c', '--consumers', default='0',
  135. help="Number of replication consumers needed in the test")
  136. parser.add_argument('-o', '--filename', default=None, help="Custom test script file name")
  137. parser.add_argument('-u', '--uuid', action='store_true',
  138. help="Display a test case uuid to used for new test functions in script")
  139. parser.add_argument('-C', '--copyright', default="Red Hat, Inc.", help="Add a copyright section in the beginning of the file")
  140. argcomplete.autocomplete(parser)
  141. args = parser.parse_args()
  142. if args.uuid:
  143. display_uuid()
  144. if args.ticket is None and args.suite is None:
  145. print('Missing required ticket number/suite name')
  146. display_usage()
  147. if args.ticket and args.suite:
  148. print('You must choose either "-t|--ticket" or "-s|--suite", ' +
  149. 'but not both.')
  150. display_usage()
  151. if int(args.suppliers) == 0:
  152. if int(args.hubs) > 0 or int(args.consumers) > 0:
  153. print('You must use "-m|--suppliers" if you want to have hubs ' +
  154. 'and/or consumers')
  155. display_usage()
  156. if not args.suppliers.isdigit() or \
  157. int(args.suppliers) > 99 or \
  158. int(args.suppliers) < 0:
  159. print('Invalid value for "--suppliers", it must be a number and it can' +
  160. ' not be greater than 99')
  161. display_usage()
  162. if not args.hubs.isdigit() or int(args.hubs) > 99 or int(args.hubs) < 0:
  163. print('Invalid value for "--hubs", it must be a number and it can ' +
  164. 'not be greater than 99')
  165. display_usage()
  166. if not args.consumers.isdigit() or \
  167. int(args.consumers) > 99 or \
  168. int(args.consumers) < 0:
  169. print('Invalid value for "--consumers", it must be a number and it ' +
  170. 'can not be greater than 99')
  171. display_usage()
  172. if args.instances:
  173. if not args.instances.isdigit() or \
  174. int(args.instances) > 99 or \
  175. int(args.instances) < 0:
  176. print('Invalid value for "--instances", it must be a number ' +
  177. 'greater than 0 and not greater than 99')
  178. display_usage()
  179. if int(args.instances) > 0:
  180. if int(args.suppliers) > 0 or \
  181. int(args.hubs) > 0 or \
  182. int(args.consumers) > 0:
  183. print('You can not mix "--instances" with replication.')
  184. display_usage()
  185. # Extract usable values
  186. ticket = args.ticket
  187. suite = args.suite
  188. if args.instances == '0' and args.suppliers == '0' and args.hubs == '0' \
  189. and args.consumers == '0':
  190. instances = 1
  191. my_topology = [True, 'topology_st', "Standalone Instance"]
  192. else:
  193. instances = int(args.instances)
  194. suppliers = int(args.suppliers)
  195. hubs = int(args.hubs)
  196. consumers = int(args.consumers)
  197. my_topology = get_existing_topologies(instances, suppliers, hubs, consumers)
  198. filename = args.filename
  199. setup_text = my_topology[2]
  200. # Create/open the new test script file
  201. if not filename:
  202. if ticket:
  203. filename = 'ticket' + ticket + '_test.py'
  204. else:
  205. filename = suite + '_test.py'
  206. try:
  207. TEST = open(filename, "w")
  208. except IOError:
  209. print("Can\'t open file:", filename)
  210. exit(1)
  211. # Write the copyright section
  212. if args.copyright:
  213. today = datetime.date.today()
  214. current_year = today.year
  215. TEST.write('# --- BEGIN COPYRIGHT BLOCK ---\n')
  216. TEST.write('# Copyright (C) {} {}\n'.format(current_year, args.copyright))
  217. TEST.write('# All rights reserved.\n')
  218. TEST.write('#\n')
  219. TEST.write('# License: GPL (version 3 or any later version).\n')
  220. TEST.write('# See LICENSE for details.\n')
  221. TEST.write('# --- END COPYRIGHT BLOCK ---\n')
  222. TEST.write('#\n')
  223. # Write the imports
  224. if my_topology[0]:
  225. topology_import = 'from lib389.topologies import {} as topo\n'.format(my_topology[1])
  226. else:
  227. topology_import = 'from lib389.topologies import create_topology\n'
  228. TEST.write('import logging\nimport pytest\nimport os\n')
  229. TEST.write('from lib389._constants import *\n')
  230. TEST.write('{}\n'.format(topology_import))
  231. TEST.write('log = logging.getLogger(__name__)\n\n')
  232. # Add topology function for non existing (in lib389/topologies.py) topologies only
  233. if not my_topology[0]:
  234. # Write the replication or standalone classes
  235. topologies_str = ""
  236. if suppliers > 0:
  237. topologies_str += " {} suppliers".format(suppliers)
  238. if hubs > 0:
  239. topologies_str += " {} hubs".format(hubs)
  240. if consumers > 0:
  241. topologies_str += " {} consumers".format(consumers)
  242. if instances > 0:
  243. topologies_str += " {} standalone instances".format(instances)
  244. # Write the 'topology function'
  245. TEST.write('\[email protected](scope="module")\n')
  246. TEST.write('def topo(request):\n')
  247. TEST.write(' """Create a topology with{}"""\n\n'.format(topologies_str))
  248. TEST.write(' topology = create_topology({\n')
  249. if suppliers > 0:
  250. TEST.write(' ReplicaRole.SUPPLIER: {},\n'.format(suppliers))
  251. if hubs > 0:
  252. TEST.write(' ReplicaRole.HUB: {},\n'.format(hubs))
  253. if consumers > 0:
  254. TEST.write(' ReplicaRole.CONSUMER: {},\n'.format(consumers))
  255. if instances > 0:
  256. TEST.write(' ReplicaRole.STANDALONE: {},\n'.format(instances))
  257. TEST.write(' })\n')
  258. TEST.write(' # You can write replica test here. Just uncomment the block and choose instances\n')
  259. TEST.write(' # replicas = Replicas(topology.ms["supplier1"])\n')
  260. TEST.write(' # replicas.test(DEFAULT_SUFFIX, topology.cs["consumer1"])\n')
  261. write_finalizer()
  262. TEST.write(' return topology\n\n')
  263. tc_id = '0'
  264. while not check_id_uniqueness(tc_id): tc_id = uuid.uuid4()
  265. # Write the test function
  266. if ticket:
  267. TEST.write('\ndef test_ticket{}(topo):\n'.format(ticket))
  268. else:
  269. TEST.write('\ndef test_something(topo):\n')
  270. TEST.write(' """Specify a test case purpose or name here\n\n')
  271. TEST.write(' :id: {}\n'.format(tc_id))
  272. TEST.write(' :setup: ' + setup_text + '\n')
  273. TEST.write(' :steps:\n')
  274. TEST.write(' 1. Fill in test case steps here\n')
  275. TEST.write(' 2. And indent them like this (RST format requirement)\n')
  276. TEST.write(' :expectedresults:\n')
  277. TEST.write(' 1. Fill in the result that is expected\n')
  278. TEST.write(' 2. For each test step\n')
  279. TEST.write(' """\n\n')
  280. TEST.write(' # If you need any test suite initialization,\n')
  281. TEST.write(' # please, write additional fixture for that (including finalizer).\n'
  282. ' # Topology for suites are predefined in lib389/topologies.py.\n\n')
  283. TEST.write(' # If you need host, port or any other data about instance,\n')
  284. TEST.write(' # Please, use the instance object attributes for that (for example, topo.ms["supplier1"].serverid)\n\n\n')
  285. # Write the main function
  286. TEST.write("if __name__ == '__main__':\n")
  287. TEST.write(' # Run isolated\n')
  288. TEST.write(' # -s for DEBUG mode\n')
  289. TEST.write(' CURRENT_FILE = os.path.realpath(__file__)\n')
  290. TEST.write(' pytest.main(["-s", CURRENT_FILE])\n\n')
  291. # Done, close things up
  292. TEST.close()
  293. print('Created: ' + filename)