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.
 
 
 
 
 
 

217 line
6.4 KiB

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