痞子泰

导航

 

环境:

系统:window7 64 

软件:pycharm

版本:2016.3.2

问题描述:

使用unittest类的时候出现问题,问题截图如下

 

Pycharm 2016.2执行单元测试遇到如下问题:

RuntimeWarning: Parent module ‘YOUR_MODULE_HERE’ not found while handling absolute import 
import unittest

解决方法,使用旧的utrunner.py文件替换当前版本,文件路径为…/PyCharm.app/Contents/helpers/pycharm/utrunner.py(macos平台)或者…\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py(windows平台)。utrunner.py的内容如下(替换文件前请先做好备份):

utrunner.py如下:

  1 import sys
  2 import imp
  3 import os
  4 import fnmatch
  5 
  6 helpers_dir = os.getenv("PYCHARM_HELPERS_DIR", sys.path[0])
  7 if sys.path[0] != helpers_dir:
  8   sys.path.insert(0, helpers_dir)
  9 
 10 from tcunittest import TeamcityTestRunner
 11 from nose_helper import TestLoader, ContextSuite
 12 from pycharm_run_utils import import_system_module
 13 from pycharm_run_utils import adjust_sys_path
 14 from pycharm_run_utils import debug, getModuleName, PYTHON_VERSION_MAJOR
 15 
 16 adjust_sys_path()
 17 
 18 os = import_system_module("os")
 19 re = import_system_module("re")
 20 
 21 modules = {}
 22 
 23 def loadSource(fileName):
 24   baseName = os.path.basename(fileName)
 25   moduleName = os.path.splitext(baseName)[0]
 26 
 27   # for users wanted to run unittests under django
 28   #because of django took advantage of module name
 29   settings_file = os.getenv('DJANGO_SETTINGS_MODULE')
 30   if settings_file and moduleName == "models":
 31     baseName = os.path.realpath(fileName)
 32     moduleName = ".".join((baseName.split(os.sep)[-2], "models"))
 33 
 34   if moduleName in modules and len(sys.argv[1:-1]) == 1: # add unique number to prevent name collisions
 35     cnt = 2
 36     prefix = moduleName
 37     while getModuleName(prefix, cnt) in modules:
 38       cnt += 1
 39     moduleName = getModuleName(prefix, cnt)
 40   debug("/ Loading " + fileName + " as " + moduleName)
 41   if os.path.isdir(fileName):
 42     fileName = fileName + os.path.sep
 43   module = imp.load_source(moduleName, fileName)
 44   modules[moduleName] = module
 45   return module
 46 
 47 def walkModules(modulesAndPattern, dirname, names):
 48   modules = modulesAndPattern[0]
 49   pattern = modulesAndPattern[1]
 50   # fnmatch converts glob to regexp
 51   prog_list = [re.compile(fnmatch.translate(pat.strip())) for pat in pattern.split(',')]
 52   for name in names:
 53     for prog in prog_list:
 54       if name.endswith(".py") and prog.match(name):
 55         modules.append(loadSource(os.path.join(dirname, name)))
 56 
 57 
 58 # For default pattern see https://docs.python.org/2/library/unittest.html#test-discovery
 59 def loadModulesFromFolderRec(folder, pattern="test*.py"):
 60   modules = []
 61   # fnmatch converts glob to regexp
 62   prog_list = [re.compile(fnmatch.translate(pat.strip())) for pat in pattern.split(',')]
 63   for root, dirs, files in os.walk(folder):
 64     files = [f for f in files if not f[0] == '.']
 65     dirs[:] = [d for d in dirs if not d[0] == '.']
 66     for name in files:
 67       for prog in prog_list:
 68         if name.endswith(".py") and prog.match(name):
 69           modules.append(loadSource(os.path.join(root, name)))
 70   return modules
 71 
 72 testLoader = TestLoader()
 73 all = ContextSuite()
 74 pure_unittest = False
 75 
 76 def setLoader(module):
 77   global testLoader, all
 78   try:
 79     module.__getattribute__('unittest2')
 80     import unittest2
 81 
 82     testLoader = unittest2.TestLoader()
 83     all = unittest2.TestSuite()
 84   except:
 85     pass
 86 
 87 if __name__ == "__main__":
 88   arg = sys.argv[-1]
 89   if arg == "true":
 90     import unittest
 91 
 92     testLoader = unittest.TestLoader()
 93     all = unittest.TestSuite()
 94     pure_unittest = True
 95 
 96     if len(sys.argv) == 2:  # If folder not provided, we need pretend folder is current
 97      sys.argv.insert(1, ".")
 98 
 99   options = {}
100   for arg in sys.argv[1:-1]:
101     arg = arg.strip()
102     if len(arg) == 0:
103       continue
104 
105     if arg.startswith("--"):
106       options[arg[2:]] = True
107       continue
108 
109     a = arg.split("::")
110     if len(a) == 1:
111       # From module or folder
112       a_splitted = a[0].split("_args_separator_")  # ";" can't be used with bash, so we use "_args_separator_"
113       if len(a_splitted) != 1:
114         # means we have pattern to match against
115         if os.path.isdir(a_splitted[0]):
116           debug("/ from folder " + a_splitted[0] + ". Use pattern: " + a_splitted[1])
117           modules = loadModulesFromFolderRec(a_splitted[0], a_splitted[1])
118       else:
119         if  os.path.isdir(a[0]):
120           debug("/ from folder " + a[0])
121           modules = loadModulesFromFolderRec(a[0])
122         else:
123           debug("/ from module " + a[0])
124           modules = [loadSource(a[0])]
125 
126       for module in modules:
127         all.addTests(testLoader.loadTestsFromModule(module))
128 
129     elif len(a) == 2:
130       # From testcase
131       debug("/ from testcase " + a[1] + " in " + a[0])
132       module = loadSource(a[0])
133       setLoader(module)
134 
135       if pure_unittest:
136         all.addTests(testLoader.loadTestsFromTestCase(getattr(module, a[1])))
137       else:
138         all.addTests(testLoader.loadTestsFromTestClass(getattr(module, a[1])),
139                      getattr(module, a[1]))
140     else:
141       # From method in class or from function
142       debug("/ from method " + a[2] + " in testcase " + a[1] + " in " + a[0])
143       module = loadSource(a[0])
144       setLoader(module)
145 
146       if a[1] == "":
147         # test function, not method
148         all.addTest(testLoader.makeTest(getattr(module, a[2])))
149       else:
150         testCaseClass = getattr(module, a[1])
151         try:
152           all.addTest(testCaseClass(a[2]))
153         except:
154           # class is not a testcase inheritor
155           all.addTest(
156             testLoader.makeTest(getattr(testCaseClass, a[2]), testCaseClass))
157 
158   debug("/ Loaded " + str(all.countTestCases()) + " tests")
159   TeamcityTestRunner().run(all, **options)

相关文档:

  1. Pycharm import RuntimeWarning after updating to 2016.2 - 简书
  2. RuntimeWarning: Parent module ‘YOUR_MODULE_HERE’ not found while handling absolute import : PY-20171
  3. RuntimeWarning: Parent module ‘settings’ not found while handling absolute import - 常城的专栏 - 博客频道 - CSDN.NET
  4. http://blog.csdn.net/wirelessqa/article/details/53465854

 本人个人博客巫章鹏的个人博客​​​​​​​

posted on 2017-08-14 14:21  痞子泰  阅读(4229)  评论(0编辑  收藏  举报