Python,导入模块进行测试 [英] Python, importing modules for testing

查看:167
本文介绍了Python,导入模块进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难设置一个简单的测试.

I am having a very hard time trying to set up a simple test.

我的项目结构如下:

project:
   models:
      __init__.py
      user.py
      constants.py
      test:
         test.py

我想测试运行test.pyuser.py py.

I want to test user.py py running test.py.

user.py

from sqlalchemy import Column, Integer, String, Text
from sqlalchemy.orm import relationship
from .models.constants import *
from .models import Base

class User(Base):
    __tablename__ = 'users'

    uid = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String, nullable=False)
    email = Column(String, nullable=False)
    picPath = Column(String, unique=True)
    description = Column(Text)

    def __repr__(self):
        return "<User(uid=%s, name=%s)>" %(self.uid, self.name)

test.py

from ..user import User, Group

def _TestUser():
    TEST_DB_URI = "postgresql://project:password@localhost:5432/projectdbtest"
    SessionMaker = sessionmaker()
    engine = create_engine(TEST_DB_URI)
    SessionMaker.configure(bind=engine)

    session = SessionMaker()
    user = User("test subject", "testsubject@gmail.com", "~/testsubject.jpg", "I am a test subject")
    session.add(user)
    session.commit()

但是,运行python3 -m test.py时出现以下错误:

However, I am getting the following error when I run python3 -m test.py:

SystemError:父模块"未加载,无法执行相对导入

SystemError: Parent module '' not loaded, cannot perform relative import

我想我可能必须将modules软件包添加到python路径中?

I think I might have to add the modules package to the python path?

推荐答案

以下几件事简化了我的测试,并且对我很好.

Here is few things, which have simplified my testing and which work for me very well.

最初,我假设我的测试用例可以在任何目录中使用.

Initially I was assuming, my test cases shall be usable from whatever directory.

实际上,没有理由使测试用例具有这种灵活性,并且从项目根目录运行所有测试的决定只会极大地简化解决方案.

In fact, there is no reason to make test cases flexible in this way and decision to run all tests from project root only strongly simplify the solution.

对于许多程序员来说,这也许很明显,但是对我来说,这是简化测试的一大步.

It might be obvious to many programmers, but to me it was big step towards simplified testing.

将生产代码与测试代码混合似乎很合逻辑,但很快就会变得混乱.

Mixing production code with test code seems logical, but soon becomes messy.

最后,我决定在项目中使用单独的tests(复数)目录,它对我来说效果很好.

Finally I have decided to use separate tests (in plural) directory in the project and it works very well for me.

优点是:

  • 测试是接近的"选择(请参见与py.test相关的下一部分),可以手动使用,也可以从其他工具(如tox)使用.
  • 无需在软件包目录中的某处寻找测试目录,它们只是生活在单独的地方
  • 可以安全地进行测试实验-因为您不在主要代码之内.
  • tests are "close" to pick (see next part related to py.test) and use manually or from other tools like tox.
  • no need to hunt for test directories somewhere in the package directories, they are simply living in separate place
  • feel safe to experiment with tests - because you are out from main code.

注意:尝试始终使用名称tests,而不使用test.保持这个简单的规则将简化您的工作,因为您将永远知道测试目录的真实名称.

Note: try to use always name tests, do not use test. Keeping this simple rule will simplify your work as you will always know the real name of your test directory.

有多种测试框架(unittestnosenose2pytest),实际上都提供了您需要的基础.

There are multiple testing frameworks (unittest, nose, nose2, pytest) and in fact all provide the basics you need.

无论如何,由于以下几个原因,我发现pytest(通过py.test命令使用)非常有趣:

Anyway, I have found pytest (with py.test command) being real fun to use for couple of reasons:

  • 可以运行大多数用其他框架编写的测试(unittest,nose ...)
  • 非常容易创建第一个测试功能.
  • 测试功能可以保持非常简单,出色的治具会为其注入所需的值.尝试之后,将不会使用其他方法.
  • 允许自然扩展测试套件
  • 非常好的开始编写代码原型并发展为生产代码:
    • 启动测试功能
    • 在同一测试文件中移出测试功能,转为独立功能
    • 移至外部模块(大多数测试代码不会更改)
    • can run most tests written in other framework (unittest, nose...)
    • very easy to create first test function.
    • test functions can be kept very simple and excellent fixtures will inject needed values into it. Once you try it, you will not use other methods.
    • allows naturally extending the test suite
    • very good to start prototyping your code and evolve to production one:
      • start in test function
      • move out of test function to independent function in the same test file
      • move to external module (and most of your testing code does not change)

      请参见选择测试布局/导入规则进行解释,并按照建议避免使用__init__.py .

      See Choosing a test layout/import rules for explanation and follow the advice to avoid using __init__.py.

      简而言之,事情会变得更简单.

      In short, things will be simpler.

      请注意,其他方法也可以使用,并且没有错-我只是想分享对我来说非常有效的方法.

      Note, that other approaches will work too and are not wrong - I just wanted to share what works very well for me.

      这篇关于Python,导入模块进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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