我可以“伪造"商品吗? python中的一个软件包(或至少一个模块)以进行测试? [英] Can I "fake" a package ( or at least a module ) in python for testing purposes?

查看:82
本文介绍了我可以“伪造"商品吗? python中的一个软件包(或至少一个模块)以进行测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用python伪造一个软件包.我想定义一些东西,以便代码可以做到

I want to fake a package in python. I want to define something so that the code can do

from somefakepackage.morefakestuff import somethingfake

somefakepackage是用代码定义的,它下面的所有内容也是如此.那可能吗?这样做的原因是为了欺骗我的单元测试,因为我在python路径中得到了一个包(或者正如我在标题中所说的,是一个模块),而这实际上只是对此单元测试的模仿.

And somefakepackage is defined in code and so is everything below it. Is that possible? The reason for doing this is to trick my unittest that I got a package ( or as I said in the title, a module ) in the python path which actually is just something mocked up for this unittest.

谢谢!

推荐答案

好的.定义一个类,将所需的内容放入其中,然后将该类分配给sys.modules["classname"].

Sure. Define a class, put the stuff you need inside that, assign the class to sys.modules["classname"].

class fakemodule(object):

    @staticmethod
    def method(a, b):
        return a+b

import sys
sys.modules["package.module"] = fakemodule

您还可以使用单独的模块(称为fakemodule.py):

You could also use a separate module (call it fakemodule.py):

import fakemodule, sys

sys.modules["package.module"] = fakemodule

这篇关于我可以“伪造"商品吗? python中的一个软件包(或至少一个模块)以进行测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆