简体   繁体   中英

Loading a python script source by filename for testing

I would like to create a test for a python 3.7+ script called foo-bar (that's the file name, and it has no .py extension):

#!/usr/bin/env python

def foo(bar):
  return bar + 42

if __name__ == '__main__':
    print(foo(1))

How can I load this file by path alone, so that I can test the foo() method? The test should NOT trigger the if main condition.

UPDATE note that this is not about executing the file from the test (ie exec('foo-bar') ), but rather loading/importing it as a module/resource, allowing the test code to execute foo() on it.

You can use the functions in importlib to load this module directly from the script file, without a .py extension.

To make this work, you need to use a loader explicitly, in this case SourceFileLoader will work.

from importlib.machinery import SourceFileLoader

foo_bar = SourceFileLoader('foo_bar', './foo-bar').load_module()

At this point, you can use the functions from inside the module:

result = foo_bar.foo(1)
assert result == 43

I think, what you can do is temporarily create copy of the file with extension. py and after importing delete it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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