I am trying to create a class with several definitions (constructors?), however when I run the class it is only running the first def that I have written and not the second one, code example below:
class Test(baseline):
def test_1(self):
global caseid
caseid = xxx
global resultfail
resultfail = "Test Failed."
self.driver.get(self.base_url)
self.login()
print('Test 1')
self.Test1TestCase()
def test_2(self):
self.driver.get(self.base_url)
self.login()
print('Test 2')
self.Test2TestCase()
Could someone please advise what changes I need to make for the Class to run both definitions? Or if this is even possible under a single Class? Cheers.
In your class Test , I am assuming baseline is a super-class since you are defining class Test with it.
You haven't created a constructor that will help class instances to be established.
class Test(baseline):
def __init__(self):
#initialize something
Next, you need to call and instantiate Test class within main (outside class)
sampleTest = Test() #instance of Test
Then you can call "methods" (functions) within class Test as,
sampleTest.test_1()
sampleTest.test_2()
Hope this is what you are looking for.
Related
Which of the following correctly describe the complete output of executing the Python Polymorphic functions below? I got this question online which I think the output is unexpected. Primary class has object inside it, shouldnt it matter? Also can we write classmethod inside a function as an argument?
class Primary(object):
def show(self):
print("Primary class is called")
class Secondary(Primary):
def show(self):
print("Secondary class is called")
def result(classmethod):
classmethod.show()
primaryobj = Primary()
secondaryobj = Secondary()
result(primaryobj)
result(secondaryobj)
The output that I got is :
Primary class is called
Secondary class is called
I want a program to call a specific class based on a parameter/variable value. However, I don't want to use any clunky if-statements. My first thought was to use the globals() function, but I couldn't get it to work. Here's an example:
class SomeClass:
def __init__():
print("Hello, world!")
class OtherClass:
def runClass(className):
# Call class based on variable className
The reason I want to do this is because there is a wide variety of classes may need to be called, and so just piling up if-statements in my code won't do it. Any help would be greatly appreciated. Thanks!
Here's how you can call a class via globals
class SomeClass:
def __init__(self):
print("Hello, world!")
def __call__(self):
return "SomeClass called"
class OtherClass:
def runClass(self, className):
globals()[className]()()
o = OtherClass()
result = o.runClass("SomeClass")
print(result)
Notice, I am instantiating and then calling it via the __call__ special method, which is the closest match to your description I could think of.
Use a dict.
name_to_class = dict(some=SomeClass,
other=OtherClass)
def factory(name):
klass = name_to_class(name)
return klass()
some_obj = factory("some")
other_obj = factory("other")
One way to solve this problem is to use a dictionary to map the values of the variable className to the corresponding class.
Try this exemple :
class SomeClass:
def init(self):
print("Hello, world!")
class OtherClass:
def init(self):
print("Goodbye, world!")
classNameToClass = {
"SomeClass": SomeClass,
"OtherClass": OtherClass
}
def runClass(className):
# Call class based on variable className
cls = classNameToClass[className]
return cls()
runClass("SomeClass") # prints "Hello, world!"
runClass("OtherClass") # prints "Goodbye, world!"
Here, the dictionary classNameToClass maps the string names of the classes (e.g. "SomeClass") to the corresponding class objects (e.g. SomeClass). Then, in the runClass function, we look up the class object using the value of the className variable, and call it to create an instance of the class.
I've found an answer. The parameter that governs the called class can just be assigned elsewhere. At first, I thought it would need some complex function, but in reality, I guess the question didn't give enough details. The class itself only uses items from whatever object is given. So, instead of having to dynamically call a class, it's as simple as:
class SomeClass:
def printHelloWorld():
print("Hello, world!")
class OtherClass:
def __init__(self, usingClass):
self.object = usingClass
def doThis():
usingClass.printHelloWorld()
x = OtherClass(SomeClass())
x.doThis()
It's on me for not giving enough information. Thank you all for your help.
I have my test case data, which is created in init function. I need to use it as a parameter for my test case, but unable to access test_case_data
class something(object):
def __init__(self, logger):
#do something
self.test_case_data = ... #Got test case data
#pytest.mark.p0
#pytest.parameterize("paramter1, parameter2, .. , ..", test_case_data)
def test_something():
#do_something
This is what my code looks like. I want to use test_case_data as a parameter, which is defined in a init function.
init isn't run until you make an instance of the class. To access:
class ClassName(object):
def __init__(self):
self.variable = "value"
instance = ClassName()
print(instance.variable)
I'm not sure what you're trying to do here but the thing to remember is that those data members declared in init don't exist until you make an instance of the class.
I have a question regarding unittest with Python! Let's say that I have a docker container set up that handles a specific api endpoint (let's say users, ex: my_site/users/etc/etc/etc). There are quite a few different layers that are broken up and handled for this container. Classes that handle the actual call and response, logic layer, data layer. I am wanting to write tests around the specific calls (just checking for status codes).
There are a lot of different classes that act as Handlers for the given endpoints. There are a few things that I would have to set up differently per one, however, each one inherits from Application and uses some methods from it. I am wanting to do a setUp class for my unittest so I don't have to re-establish this each time. Any advice will help. So far I've mainly seen that inheritance is a bad idea with testing, however, I am only wanting to use this for setUp. Here's an example:
class SetUpClass(unittest.TestCase):
def setUp(self):
self._some_data = data_set.FirstOne()
self._another_data_set = data_set.SecondOne()
def get_app(self):
config = Config()
return Application(config,
first_one=self._some_data,
second_one=self._another_data_set)
class TestFirstHandler(SetUpClass, unittest.TestCase):
def setUp(self):
new_var = something
def tearDown(self):
pass
def test_this_handler(self):
# This specific handler needs the application to function
# but I don't want to define it in this test class
res = self.fetch('some_url/users')
self.assertEqual(res.code, 200)
class TestSecondHandler(SetUpClass, unittest.TestCase):
def setUp(self):
different_var_thats_specific_to_this_handler = something_else
def tearDown(self):
pass
def test_this_handler(self):
# This specific handler needs the application to function
# but I don't want to define it in this test class
res = self.fetch('some_url/users/account/?something_custom={}'.format('WOW'))
self.assertEqual(res.code, 200)
Thanks again!!
As mentioned in the comments, you just need to learn how to use super(). You also don't need to repeat TestCase in the list of base classes.
Here's the simple version for Python 3:
class TestFirstHandler(SetUpClass):
def setUp(self):
super().setUp()
new_var = something
def tearDown(self): # Easier to not declare this if it's empty.
super().tearDown()
def test_this_handler(self):
# This specific handler needs the application to function
# but I don't want to define it in this test class
res = self.fetch('some_url/users')
self.assertEqual(res.code, 200)
I am trying to create a class in the superclass
I have a superclass in SuperTest.py:
class SuperTest():
def func(self):
return Test2()
And test.py
from SuperTest import *
class Test(SuperTest):
def create(self):
return self.func()
class Test2(SuperTest):
pass
test = Test()
print test.create()
Then I have an error NameError: global name 'Test2' is not defined.
Is it possible to do that? How to handle the scope? As I know I can't mutually import the classes recursively.
I will be getting some class names in the superclass function. It is important for me to dynamically create the class in it.
Try this,
class SuperTest(object):
def func(self):
from Test import Test2
return Test2()