在我的包的子包中运行 python 脚本

2024-04-03

无法弄清楚正确,python 2.x 首选方式进行相对导入,以便我可以将测试脚本放在一个子包中,并使这些测试脚本能够测试我的库。

$ farm\testpad\testpad.py
Traceback (most recent call last):
  File "C:\farm\testpad\testpad.py", line 4, in <module>
    from ..animals.dog import dog
ValueError: Attempted relative import in non-package

$ python -m farm\testpad\testpad
C:\Python27\python.exe: No module named farm\testpad\testpad

在下面的示例中,我需要修改什么才能实现我想要的功能?请并感谢您提供的任何帮助。

e.g.

封装结构:

farm/
    __init__.py # empty
    animals/
        __init__.py # empty
        dog.py
    testpad/
        __init__.py # empty
        testpad.py

dog.py

import sys
import os

class dog():
  def __init__(self, name):
    self.name = name

  def speak(self):
    print "woof"

测试板.py

import os
import sys

from ..animals.dog import dog

# create a dog and test its speak action
def testpad():
  d = dog("Allen")
  d.speak()

if __name__ == "__main__":
  testpad()

三件事:

  • 始终从项目的根目录运行测试脚本。这个简单的规则不会造成任何损害,并且会简化您的场景
  • 更喜欢绝对进口
  • -m选项python需要点形式的模块

将其应用到您的代码中

Modify testpad.py

import os
import sys

from farm.animals.dog import dog

# Create a dog and test its speak action

    def testpad():
      d = dog("Allen")
      d.speak()

    if __name__ == "__main__":
      testpad()

调用它来自python -m <module>

$ python -m farm.testpad.testpad
woof

奖励 - 测试来自nose

对于我的测试,我使用以下模式

  • 将所有测试代码保留在名为的项目子目录中test或更好tests
  • use nose测试框架

处于项目的根目录

Install nose:

$ pip install nose

什么创建命令nosetests

重新组织你的代码

$ mkdir tests
$ mv farm/testpad/testpad.py tests/test_animals.py
$ rm -rf farm/testpad/

运行测试(目前只有一个)

最简单的方法,做什么工作,但尽量保持输出最小:

$ nosetests
.
----------------------------------------------------------------------
Ran 1 test in 0.003s

OK

正如你所看到的,nose 正在自己发现测试用例(搜索以test)

让它更详细一点:

$ nosetests -v
test_animals.testpad ... ok

----------------------------------------------------------------------
Ran 1 test in 0.003s

OK

现在您知道进行了哪些测试。

要查看捕获的输出,请使用-s switch:

$ nosetests -vs
test_animals.testpad ... woof
ok

----------------------------------------------------------------------
Ran 1 test in 0.003s

OK

添加更多测试test_animals.py

import os
import sys

# create a dog and test its speak action
def test_dog():
    from farm.animals.dog import dog
    d = dog("Allen")
    d.speak()

def test_cat():
    from farm.animals.dog import cat
    c = cat("Micy")
    d.speak()

def test_rabbit():
    from farm.animals.dog import rabbit
    r = rabbit()
    r.speak()

Test it:

$ nosetests -vs
test_animals.test_dog ... woof
ok
test_animals.test_cat ... ERROR
test_animals.test_rabbit ... ERROR

======================================================================
ERROR: test_animals.test_cat
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/javl/Envs/so/local/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/home/javl/sandbox/so/testpad/tests/test_animals.py", line 12, in test_cat
    from farm.animals.dog import cat
ImportError: cannot import name cat

======================================================================
ERROR: test_animals.test_rabbit
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/javl/Envs/so/local/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/home/javl/sandbox/so/testpad/tests/test_animals.py", line 17, in test_rabbit
    from farm.animals.dog import rabbit
ImportError: cannot import name rabbit

----------------------------------------------------------------------
Ran 3 tests in 0.004s

FAILED (errors=2)

Add --pdb切换到调试器(如果你安装了ipdbplugin,你可能会使用--ipdb):

$ nosetests -vs --pdb
test_animals.test_dog ... woof
ok
test_animals.test_cat ... > /home/javl/sandbox/so/testpad/tests/test_animals.py(12)test_cat()
-> from farm.animals.dog import cat
(Pdb) l
  7         from farm.animals.dog import dog
  8         d = dog("Allen")
  9         d.speak()
 10  
 11     def test_cat():
 12  ->     from farm.animals.dog import cat
 13         c = cat("Micy")
 14         d.speak()
 15  
 16     def test_rabbit():
 17         from farm.animals.dog import rabbit
(Pdb) 

Use h或者找到一些调试器教程,它是很棒的工具

真实的测试用例应断言行为符合预期。

断言打印值符合预期

当您打印到 stdout 时,我们可以使用模拟捕获输出(在 Python 2.x 中您必须安装它,在 Python 3.x 中您from unittest import mock):

$ pip install mock

并修改你的test_animals.py:

from mock import patch
from StringIO import StringIO

# create a dog and test its speak action
@patch("sys.stdout", new_callable=StringIO)
def test_dog(mock_stdout):
    from farm.animals.dog import Dog
    d = Dog("Allen")
    d.speak()
    assert mock_stdout.getvalue() == "woof\n"

@patch("sys.stdout", new_callable=StringIO)
def test_cat(mock_stdout):
    from farm.animals.cat import Cat
    c = Cat("Micy")
    c.speak()
    assert mock_stdout.getvalue() == "mnau\n"

@patch("sys.stdout", new_callable=StringIO)
def test_rabbit(mock_stdout):
    from farm.animals.rabbit import Rabbit
    r = Rabbit("BB")
    r.speak()
    assert mock_stdout.getvalue() == "Playboy, Playboy\n"

我的品味的最终测试用例test_mytaste.py

def test_dog():
    from farm.animals.dog import Dog
    d = Dog("Allen")
    sound = d.speak()
    assert sound == "woof", "A dog shall say `woof`"

def test_cat():
    from farm.animals.cat import Cat
    c = Cat("Micy")
    sound = c.speak()
    assert sound == "mnau", "A cat shall say `mnau`"

def test_rabbit():
    from farm.animals.rabbit import Rabbit
    r = Rabbit("BB")
    sound = r.speak()
    assert sound == "Playboy, Playboy", "A Rabbit shall say ..."

这需要您重构代码(类名以大写开头,speak方法不打印但返回声音)。

事实上,您可能会开始从测试用例编写代码,然后添加经过测试的模块,当您从一开始就开始考虑实际使用时,这通常会带来更好的设计。

选择性调用测试用例

鼻子非常适合搜索测试用例(通常以test),但有时您可能会专注于特定测试或使用不同名称的 python 文件。你可以告诉nose仅使用一个测试文件:

$ nosetests -vs tests/test_mytaste.py 
test_mytaste.test_dog ... ok
test_mytaste.test_cat ... ok
test_mytaste.test_rabbit ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.002s

OK

甚至目标nose从中运行特定测试:

$ nosetests -vs tests/test_mytaste.py:test_dog
test_mytaste.test_dog ... ok

----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在我的包的子包中运行 python 脚本 的相关文章

随机推荐

  • jQuery 切换动画

    我有这个 jQuery document ready function panel hide login toggle function panel animate height 150 padding 20px 0 backgroundC
  • Bash 中常量的命名约定是什么?

    在 shell 脚本中 即使我使用Java or Python样式命名约定 我仍然不清楚命名常量 许多约定建议我使用 大写字母 和 下划线 一起命名常量 例如MY CONSTANT PI 但在Bash 这可能与环境变量 https stac
  • 使用 Yosup 时如何查找最新的 MD5、KEY 和 VERSION

    我发现在使用 yowsup 时出现 old version 错误时 向 Whatsapp 服务器注册有时会失败 Yosup 旧版本错误 https stackoverflow com questions 35877803 yowsup ol
  • GAE PHP 应用程序:无法找到包装器“gs”

    我正在编写一些非常简单的代码standardphp73 Google App 引擎环境 遵循此处的文档 https cloud google com appengine docs standard php googlestorage htt
  • Node-sass 不理解波浪号

    探索angular cli对于最近发布的 Angular2 的 RC1 我遇到了奇怪的问题 node sass在 sass 插件中angular cli不解析 在包名称之前抛出以下错误 Error File to import not fo
  • 非常简单的DNS服务器

    我有一台 Linux 服务器 有一个临时无线网络供客户端连接 连接后 我希望用户始终被重定向到它自己的 Web 服务器 无论他们输入什么 URL 最大的解决方案是设置一个完整的 DNS 服务器 使用 BIND 或等效服务器 但这似乎有点过头
  • QString 的运算符 <<

    为 QString 实现 std ostream operator lt lt std ostream stream const QString str stream lt lt str toAscii constData or strea
  • 浏览器也可以缓存嵌入的 Base64 图像吗?

    我想知道是否有任何现代浏览器实际上缓存了嵌入的图像 base64 字符串 这在不久的将来有可能吗 基于 W3C 或主要浏览器的官方文档 我不这么认为 因为你错过了Resource Identifier作为缓存图像的键 对于嵌入图像 您只有数
  • 使用 pandas 标记每组的每 N 行

    我有一个数据框 其中包含客户信息及其购买详细信息 我正在尝试添加一个新列 指示同一客户每进行第三次购买 下面给出的是数据框 customer name bill no date Mark 101 2018 10 01 Scott 102 2
  • input:not(:placeholder-shown) ~ 标签选择器不适用于自动填充

    我在输入字段中有浮动占位符 当我们未提供输入值时 占位符将出现在中心 如下图所示 电子邮件和密码为占位符 现在 当您向电子邮件提供值时 它确实如下所示 观察提供值后 电子邮件和密码已被提取 当浏览器开始从页面加载时保存的凭据 如用户名 电子
  • NSCalendar NSDateComponents weekofYear 返回 1,日期为 2014-12-31

    我想获得日期为 2014 12 31 的 weekofYear 但它总是返回 1 而不是 52 这是我的代码 NSCalendar calendar NSCalendar currentCalendar NSUInteger unitFla
  • 为什么 Google 的 pandas_datareader 不起作用?

    我尝试通过以下代码从谷歌财经获取数据 import pandas datareader data as wb import datetime as dt start dt datetime 2015 1 1 end dt datetime
  • nginx php 友好的 URL 重定向,不会干扰 index.php 导致 /index

    我尝试了很多不同的配置来启用任何以 php 结尾的请求的永久重定向 以重定向到不带 php 的自身 问题是 我无法获得将使用 index php 发送到任何目录的请求重定向到 而不是 index 的规则 Example 期望的行为 blog
  • 如何获取系统设备语言,swift iOS

    如何使用 swift iOS 获取系统设备语言 而不是应用程序语言 我没有遇到任何问题 我想从以下位置获取设备语言设置 gt 常规 gt 语言该用户将语言设置为 我尝试了下面的代码 let appLang Locale preferredL
  • 如何处理异步。护照和猫鼬的 findOrCreate 方法

    身份验证模块 Passport 需要 FindOrCreate 方法才能进行登录 我使用 mongoose 来保存我的用户 其架构如下 var UserSchema new Schema firstname String lastname
  • AspectJ Maven 插件无法编译我的项目

    我尝试使用aspectj maven插件使用aspectj编译器来编译项目 然后尝试将类打包到 war 文件中 不幸的是 它不适用于以下配置 pom xml
  • 限制属性的字符串长度

    当我试图找出一个更大的问题时出现了这个问题 为了简单起见 我省略了这个问题 我必须用 C 表示某种数据结构 它是一种用于与外部系统通信的协议 因此 它具有一系列具有预定义长度和整数 或其他更复杂的数据 的字符串 我们假设 SYSTEM fo
  • Android WebRtc 本地视频流无法在棉花糖上显示,但可以在棒棒糖上显示

    添加的库 libjingle peerconnection jar Version 1 7 0 101 libjingle peerconnection so so 等级依赖性 fi vtt nubomedia utilities andr
  • 无法在VS2010/SQL Server 2012中使用SSIS SSDT

    我在本地计算机上安装了完整版本的 Sql Server 2012 并从安装包 和更新 安装了 SSDT 然后 我打开 SSDT Visual Studio 应用程序并安装 Microsoft 的 SSDT 包 该包似乎工作正常 但是 当我尝
  • 在我的包的子包中运行 python 脚本

    无法弄清楚正确 python 2 x 首选方式进行相对导入 以便我可以将测试脚本放在一个子包中 并使这些测试脚本能够测试我的库 farm testpad testpad py Traceback most recent call last