简体   繁体   English

在单元测试中导入库的位置? 蟒蛇

[英]Where to import libraries in unit tests ? Python

I have to write a test file like this: 我必须写一个这样的测试文件:

import unittest

from mylibrary import some_crazy_func

class TestSomething(unittest.TestCase):
    def test_some_crazy_func_that_needs_io_open(self):
        # Opens file
        # Calls function
        # assert outputs

But I'm unsure where is the "pythonic location" where I should import the library (let's say io ). 但我不确定我应该导入库的“pythonic位置”(让我们说io )。

Should it be at the top: 它应该在顶部:

import io
import unittest

from mylibrary import some_crazy_func

class TestSomething(unittest.TestCase):
    def test_some_crazy_func_that_needs_io_open(self):
         expected = ['abc', 'def', 'xyz']
         with io.open('somestaticfile.txt', 'r') as fin:
             outputs = [some_crazy_func(line) for line in fin]
         assert outputs == expected

Or within the TestCase 's function: 或者在TestCase的功能范围内:

import unittest

from mylibrary import some_crazy_func

class TestSomething(unittest.TestCase):
    def test_some_crazy_func_that_needs_io_open(self):
         import io
         expected = ['abc', 'def', 'xyz']
         with io.open('somestaticfile.txt', 'r') as fin:
             outputs = [some_crazy_func(line) for line in fin]
         assert outputs == expected

Or is it before the TestCase function and at the object initialization: 或者它是在TestCase函数之前和对象初始化时:

import unittest

from mylibrary import some_crazy_func

class TestSomething(unittest.TestCase):
    import io
    def test_some_crazy_func_that_needs_io_open(self):
         expected = ['abc', 'def', 'xyz']
         with io.open('somestaticfile.txt', 'r') as fin:
             outputs = [some_crazy_func(line) for line in fin]
         assert outputs == expected

See PEP8: https://www.python.org/dev/peps/pep-0008/#id23 参见PEP8: https ://www.python.org/dev/peps/pep-0008/#id23

It states, 它指出,

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. 导入总是放在文件的顶部,就在任何模块注释和文档字符串之后,以及模块全局变量和常量之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM