社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在Python中测试回退导入

PartialOrder • 4 年前 • 429 次点击  

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
 
429 次点击  
文章 [ 1 ]  |  最新文章 4 年前
sanyash
Reply   •   1 楼
sanyash    5 年前

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

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

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