You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

221 rivejä
6.7 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import sys
  5. if __name__=="__main__":
  6. sys.path.extend([".", "app", "lib"])
  7. import webnotes
  8. import unittest
  9. from webnotes.model.meta import has_field
  10. from webnotes.model.code import load_doctype_module, get_module_name
  11. from webnotes.model.doctype import get_link_fields
  12. from webnotes.utils import cstr
  13. def make_test_records(doctype, verbose=0):
  14. webnotes.flags.mute_emails = True
  15. if not webnotes.conn:
  16. webnotes.connect()
  17. for options in get_dependencies(doctype):
  18. if options.startswith("link:"):
  19. options = options[5:]
  20. if options == "[Select]":
  21. continue
  22. if options not in webnotes.test_objects:
  23. webnotes.test_objects[options] = []
  24. make_test_records(options, verbose)
  25. make_test_records_for_doctype(options, verbose)
  26. def get_modules(doctype):
  27. module = webnotes.conn.get_value("DocType", doctype, "module")
  28. test_module = load_doctype_module(doctype, module, "test_")
  29. if test_module: reload(test_module)
  30. return module, test_module
  31. def get_dependencies(doctype):
  32. module, test_module = get_modules(doctype)
  33. options_list = list(set([df.options for df in get_link_fields(doctype)] + [doctype]))
  34. if hasattr(test_module, "test_dependencies"):
  35. options_list += test_module.test_dependencies
  36. if hasattr(test_module, "test_ignore"):
  37. for doctype_name in test_module.test_ignore:
  38. if doctype_name in options_list:
  39. options_list.remove(doctype_name)
  40. return options_list
  41. def make_test_records_for_doctype(doctype, verbose=0):
  42. module, test_module = get_modules(doctype)
  43. if verbose:
  44. print "Making for " + doctype
  45. if hasattr(test_module, "make_test_records"):
  46. webnotes.test_objects[doctype] += test_module.make_test_records(verbose)
  47. elif hasattr(test_module, "test_records"):
  48. webnotes.test_objects[doctype] += make_test_objects(doctype, test_module.test_records, verbose)
  49. elif verbose:
  50. print_mandatory_fields(doctype)
  51. def make_test_objects(doctype, test_records, verbose=None):
  52. records = []
  53. for doclist in test_records:
  54. if "doctype" not in doclist[0]:
  55. doclist[0]["doctype"] = doctype
  56. d = webnotes.bean(copy=doclist)
  57. if webnotes.test_objects.get(d.doc.doctype):
  58. # do not create test records, if already exists
  59. return []
  60. if has_field(d.doc.doctype, "naming_series"):
  61. if not d.doc.naming_series:
  62. d.doc.naming_series = "_T-" + d.doc.doctype + "-"
  63. # submit if docstatus is set to 1 for test record
  64. docstatus = d.doc.docstatus
  65. d.doc.docstatus = 0
  66. d.insert()
  67. if docstatus == 1:
  68. d.submit()
  69. records.append(d.doc.name)
  70. return records
  71. def print_mandatory_fields(doctype):
  72. print "Please setup make_test_records for: " + doctype
  73. print "-" * 60
  74. doctype_obj = webnotes.get_doctype(doctype)
  75. print "Autoname: " + (doctype_obj[0].autoname or "")
  76. print "Mandatory Fields: "
  77. for d in doctype_obj.get({"reqd":1}):
  78. print d.parent + ":" + d.fieldname + " | " + d.fieldtype + " | " + (d.options or "")
  79. print
  80. def export_doc(doctype, docname):
  81. import json
  82. doclist = []
  83. ignore_list = ["name", "owner", "creation", "modified", "modified_by", "idx", "naming_series",
  84. "parenttype", "parent", "docstatus"]
  85. make_test_records(doctype)
  86. meta = webnotes.get_doctype(doctype)
  87. for d in webnotes.bean(doctype, docname):
  88. new_doc = {}
  89. for key, val in d.fields.iteritems():
  90. if val and key not in ignore_list:
  91. df = meta.get_field(key, d.parent or None, d.parentfield or None)
  92. if df and df.fieldtype == "Link":
  93. val = (webnotes.test_objects.get(df.options) or [val])[0]
  94. elif df and df.fieldtype == "Select" and df.options and df.options.startswith("link:"):
  95. val = (webnotes.test_objects.get(df.options[5:]) or [val])[0]
  96. if not df or df.reqd == 1:
  97. new_doc[key] = val
  98. doclist.append(new_doc)
  99. print json.dumps(doclist, indent=4, sort_keys=True).replace(" ", "\t")
  100. def run_unittest(doctype, verbose=False):
  101. module = webnotes.conn.get_value("DocType", doctype, "module")
  102. test_module = get_module_name(doctype, module, "test_")
  103. make_test_records(doctype, verbose=verbose)
  104. try:
  105. exec ('from %s import *' % test_module) in globals()
  106. del sys.argv[1:]
  107. unittest.main()
  108. except ImportError, e:
  109. print "No test module."
  110. def run_all_tests(verbose):
  111. import os
  112. test_suite = unittest.TestSuite()
  113. for path, folders, files in os.walk("."):
  114. if 'locale' in folders: folders.remove('locale')
  115. # print path
  116. for filename in files:
  117. filename = cstr(filename)
  118. if filename.startswith("test_") and filename.endswith(".py"):
  119. # print filename[:-3]
  120. _run_test(path, filename, verbose, test_suite=test_suite, run=False)
  121. # webnotes.conn.rollback()
  122. # webnotes.test_objects = {}
  123. unittest.TextTestRunner(verbosity=1+(verbose and 1 or 0)).run(test_suite)
  124. def _run_test(path, filename, verbose, test_suite=None, run=True):
  125. import os, imp
  126. from webnotes.modules.utils import peval_doclist
  127. if not test_suite:
  128. test_suite = unittest.TestSuite()
  129. if os.path.basename(os.path.dirname(path))=="doctype":
  130. txt_file = os.path.join(path, filename[5:].replace(".py", ".txt"))
  131. with open(txt_file, 'r') as f:
  132. doctype_doclist = peval_doclist(f.read())
  133. doctype = doctype_doclist[0]["name"]
  134. make_test_records(doctype, verbose)
  135. module = imp.load_source(filename[:-3], os.path.join(path, filename))
  136. test_suite.addTest(unittest.TestLoader().loadTestsFromModule(module))
  137. if run:
  138. unittest.TextTestRunner(verbosity=1+(verbose and 1 or 0)).run(test_suite)
  139. def main():
  140. import argparse
  141. parser = argparse.ArgumentParser(description='Run tests.')
  142. parser.add_argument('-d', '--doctype', nargs=1, metavar = "DOCTYPE",
  143. help="test for doctype")
  144. parser.add_argument('-v', '--verbose', default=False, action="store_true")
  145. parser.add_argument('-e', '--export', nargs=2, metavar="DOCTYPE DOCNAME")
  146. parser.add_argument('-a', '--all', default=False, action="store_true")
  147. parser.add_argument('-m', '--module', default=1, metavar="MODULE")
  148. args = parser.parse_args()
  149. if not webnotes.conn:
  150. webnotes.connect()
  151. webnotes.flags.print_messages = args.verbose
  152. webnotes.flags.in_test = True
  153. if args.doctype:
  154. run_unittest(args.doctype[0], verbose=args.verbose)
  155. elif args.all:
  156. run_all_tests(args.verbose)
  157. elif args.export:
  158. export_doc(args.export[0], args.export[1])
  159. elif args.module:
  160. import importlib
  161. test_suite = unittest.TestSuite()
  162. module = importlib.import_module(args.module)
  163. if hasattr(module, "test_dependencies"):
  164. for doctype in module.test_dependencies:
  165. make_test_records(doctype, verbose=args.verbose)
  166. test_suite.addTest(unittest.TestLoader().loadTestsFromModule(sys.modules[args.module]))
  167. unittest.TextTestRunner(verbosity=1+(args.verbose and 1 or 0)).run(test_suite)
  168. if __name__=="__main__":
  169. main()