0

I can't figure out why my test file is asking for more arguments. I've implemented argparse in my foo file, but not in the test file.

$ python test_foo.py
usage: test_foo.py [-h] inputfile dictionary
test_foo.py: error: too few arguments

If I pass in more arguments:

$ python test_foo.py inputfile.txt dictionary.txt

[OUTPUT FROM FOO]
Traceback (most recent call last):
  File "test_foo.py", line 22, in <module>
    unittest.main()
  File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/main.py", line 94, in __init__
    self.parseArgs(argv)
  File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/main.py", line 149, in parseArgs
    self.createTests()
  File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/main.py", line 158, in createTests
    self.module)
  File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 130, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 100, in loadTestsFromName
    parent, obj = obj, getattr(obj, part)
AttributeError: 'module' object has no attribute 'input'

I also don't know why it outputs the result of foo, since I'm only asking it to import two functions. Here's my code:

#test_foo.py
import unittest
from foo import my_function, another_function
class TestFooMethods(unittest.TestCase):
  [everything commented out]
if __name__ == '__main__':
  unittest.main()

and:

#foo.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('inputfile', action="store")
parser.add_argument('dictionary', action="store")

def my_function(inputfile):
  [code]

def another_function(dictionary):
  [code]

my_function(inputfile)
another_function(dictionary)
print(OUTPUT FROM FOO)

Thanks!

calun
  • 3
  • 1

2 Answers2

1

When you run import foo, the file foo.py in running. That's why you're being asked for arguments. You should add if "__main__" == __name__: and put all your code in it (except function definitions and imports).

When you run foo.py, its __name__ will be "__main__". But when you import it, its name will be "foo".

Ella Sharakanski
  • 2,683
  • 3
  • 27
  • 47
0

following up on Ella Shar' answer, here's a quick demonstartion:

# foo.py

def bar(foo):
    return foo

print 'hi'

running

>>> from foo import bar

outputs:

>>> hi

correct way:

# foo.py

def bar(foo):
    return foo

if __name__ == 'main':
    print 'hi'

outputs: will simply prompt you for next command

HassenPy
  • 2,083
  • 1
  • 16
  • 31