Python社区  »  Python

在Python中测试回退导入

PartialOrder • 7 月前 • 52 次点击  

pip ,但如果用户没有安装正确的模块,我想提供一个回退模块。

我想在不切换环境的情况下进行单元测试。因此如下:

文件a.py

"""
This module would, under ideal circumstances, be installed with pip
but maybe not...
"""
class Foo():

    @staticmethod
    def test():
        return "This is the module we'd like to import"

"""
This is my own fallback module
"""
class Foo():

    @staticmethod
    def test():
        return "This is the fallback module"

文件c.py

try:
    from sandbox.a import Foo
except ImportError:
    from sandbox.b import Foo

"""This is the module in my app that would actually use Foo"""

这是测试,d.py

import sys

def test_it():
    sys.modules['a'] = None
    import sandbox.c as c
    s = c.Foo.test()
    assert s == "This is the fallback module"

E       AssertionError: assert 'This is the ...ike to import' == 'This is the fallback module'
E         - This is the module we'd like to import
E         + This is the fallback module

sandbox/d.py:8: AssertionError

测试这个的正确方法是什么,以便我确保用户永远不会得到importerrorror(如果他们没有模块 a.py b.py 在这种情况下?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54686
 
52 次点击  
分享到微博
文章 [ 1 ]  |  最新文章 7 月前
sanyash
Reply   •   1 楼
sanyash    1 年前

据我所知,您的结构如下:

- dir sandbox
-- file a.py
-- file b.py
-- file c.py
- file d.py

sys.modules['a'] = None sys.modules['sandbox.a'] = None 这很管用。