1

I have a python class that requires a command line argument:

class SomeClass:
    
    request = sys.argv[1] + ".json"
    
    def __init__(self_:
       self.req = request

i'd run someClass.py on the commandline i.e. python someClass 1234, which would set the json to 1234.json.

I want a second class, testClass.py, to be able to test methods inside of the main class. But first, i just want to make sure its connected by printing variables:

from someClass import  SomeClass

i = SomeClass()

print(i.req)

if i run python testClass.py (without any input), i get a missing input error,

error: the following arguments are required: input

so if i run python testClass.py 1234, i get

none

i just want to know how to pull the class in and make sure its provided with an argument so i can test individual components inside of it.

1
  • 2
    Can't you build someClass so that the constructor gets an argument that you can fill in with sys.argv? Commented Feb 1, 2021 at 21:25

2 Answers 2

1

Just overwrite request in every test that needs it:

import unittest
from x import SomeClass

class TestClass(unittest.TestCase):
    def setUp(self):
        SomeClass.request = ''

In general, don't make classes which set themselves up. Make the class take parameters which are not defaulted.

You can always make higher level code which supplies default values.

Sign up to request clarification or add additional context in comments.

2 Comments

If sys.argv[1] doesn't exist, this will raise an IndexError immediately upon trying to import x, before you have a chance to patch SomeClass.request.
Yeah, another reason to not do that.
0

Don't make your class depend on sys.argv in the first place.

class SomeClass:        
    def __init__(self, base):
       self.req = base + ".json"

Then

from someClass import  SomeClass

i = SomeClass(sys.argv[1])  # or any other value

print(i.req)

2 Comments

Its a requirement for the deliverable, set by a requirement analyst. Wish i could change it ! Any other ideas?
You can examine the value of sys.argv before you import SomeClass, and assign to it manually if necessary. Your error message suggests that something like argparse is trying and failing to parse the arguments as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.