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.
 
 
 
 
 
 

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