在单元测试中从何处导入库?Python

2024-04-19 00:00:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须这样写一个测试文件:

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

但是我不确定我应该导入库的“pythonic位置”在哪里(比如io)。你知道吗

如果在顶部:

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

或者在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

或者是在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

Tags: fromioimportdeflinesomeunittestopen