unit tests python "__init__() takes exactly 2 arguments (1 given)" - python

i'm having a problem in my unit tests, i don't know why, I'm gotting the following stack:
Traceback (most recent call last):
File "novaapiclient_tests.py", line 11, in test_create_server
nova = novaapiclient.NovaAPIClient()
TypeError: __init__() takes exactly 2 arguments (1 given)
follow my test code:
class TestFunction(unittest.TestCase):
def setUp(self):
self.nova = novaapiclient.NovaAPIClient()
def test_create_server(self):
self.setUp()
lsbf = self.nova.lst_of_servers(self.nova.listServers())
image = "3f9e6696-2ed2-4e06-ae16-c828062addbe"
flavor = "m1.tiny"
name = "testing_unit"
self.nova.createServer(image, flavor, name)
time.sleep(60)
lsaf = self.nova.lst_of_servers(self.nova.listServers())
if(len(lsbf) < len(lsaf)):
assertTrue(True)
else:
assertTrue(False)
def delete_server(self):
self.setUp()
serv_id = "13e0c3de-d736-47ec-bc22-3a794aa3e2a9"
self.nova.deleteServer(serv_id)
ls = self.nova.lst_of_servers(self.nova.listServers())
j = 0
fin = False
while(j < 3 and not fin):
time.sleep(75)
for i in range(len(ls)):
if(serv_id == str(ls[i])):
assertTrue(False)
break
assertTrue(True)
fin = True
break
j += 1
I tried to create a init method and cut the "self" in the methods, but i continues printing the error.

The novaapiclient.NovaAPIClient constructor needs to receive an argument, but you aren't passing any.
In this question of yours you did pass an argument to novaapiclient.NovaAPIClient, so I assume you need to do something similar.

Related

Can someone explain to me how to resolve the argument error below with the use of my code?

The error here is on positional argument error where the code can not execute because of the position argument error on this line of code 'Customer_Cars_1 = Customer1.requestCar()'. I got an error of "TypeError: rentCarOnHourlyBasis() missing 1 required positional argument: 'n' " which I am not sure if It has been resolved. I need an explicit explanation on how to resolve all the errors listed above
THE ERROR:
Traceback (most recent call last):
File "c:/Users/CRIME ALERT 3/Documents/project for python/car_rent2.py", line 79, in
<module>
CarRtl.rentalPackages(Customer_Cars_1)
TypeError: rentalPackages() takes 1 positional argument but 2 were given
MY CODE
class CarRental:
def __init__(self, stock):
self.stock = stock
def displayStock(self):
print(f"Welcome To Ayodeji Autos.... \n \n \nWe have currently {self.stock} cars
available to rent\n \n \n")
return self.stock
def rentalPackages(self):
numCars = CarRental(int(n))
numCars.rentalPackages
option = int(input('Ayodeji Autos Rental Packages \nOptions: \n 1 - Hourly
Basis\n**************************************\nHow long do you want to rent a car: '))
try:
option = int(option)
except ValueError:
print("That's not a positive integer!")
return 1
if option == 1:
CarRental.rentCarOnHourlyBasis(numCars)
else:
return CarRental.displayStock()
def rentCarOnHourlyBasis(self, n):
if n <= 0:
print('Number of cars should be positive!')
elif n > self.stock:
print(f'Sorry! We have currently {self.stock} bikes available to rent.')
return None
else:
now = datetime.datetime.now()
print(f'You have rented a {n} car(s) on hourly basis today at {now.hour} hours.')
print("You will be charged $5 for each hour per car.")
print("We hope that you enjoy our service.")
self.stock -= n
return now
class Customer:
def requestCar(self):
cars = input("How many cars would you like to rent?")
try:
cars = int(cars)
except ValueError:
print("That's not a positive integer!")
return 1
if cars < 1:
print(f"{cars} is an Invalid input. Number of cars should be greater than zero!")
return 1
else:
self.cars = cars
return self.cars
if __name__ == '__main__':
stock = 10
CarRtl = CarRental(stock)
CarRtl.displayStock()
Customer1 = Customer()
Customer_Cars_1 = Customer1.requestCar()
CarRtl.rentalPackages(Customer_Cars_1)
You should add another positional argument as the first argument that is passed in a method is an instance of the object.
CarRtl.rentalPackages(Customer_Cars_1) in this line of code, you are passing 2 arguments to rentalPackages. First one is the instance of the object (whenever we call a method of any class on the object of that class, the instance of that object is get automatically passed as an argument in that method. In this case the object is CarRtl), and the second argument is Customer_Cars_1.
But,
In the class CarRental the function rentalPackages(self) takes only one argument that is self where, self represents the instance of object.
If you want to pass another argument in that function you should add one more argument while defining the function. Like this, rentalPackages(self, AnotherArgumentVariableName)

Pickle errors with Python 3

I'm converting some code from Python 2 to Python 3, and I have hard time with a pickle problem! Here is a simple example of what I'm trying to do:
class test(str):
def __new__(self, value, a):
return (str.__new__(self, value))
def __init__(self, value, a):
self.a = a
if __name__ == '__main__':
import pickle
t = test("abs", 5)
print (t)
print( t.a)
wdfh = open("./test.dump", "wb")
pickle.dump(t, wdfh)
wdfh.close()
awfh = open("./test.dump", "rb")
newt = pickle.load(awfh)
awfh.close()
print (t)
print (newt.a)
This works just fine with Python 2 but I have the following error with Python 3:
Traceback (most recent call last):
File "test.py", line 21, in
newt = pickle.load(awfh)
TypeError: new() takes exactly 3 arguments (2 given)
I do not understand what is the difference, any idea?
The problem here is that your code only works with protocol 0 or 1. By default, Python 2 uses protocol 0, whereas Python 3 uses protocol 3.
For protocol 2 and above you can't have additional arguments to the __new__ method unless you implement the __getnewargs__ method.
In this case simply adding:
def __getnewargs__(self):
return (str(self),self.a)
should do the trick.
Or you could stick with protocol 0 or 1 and change the dump call:
pickle.dump(t, wdfh, 0)

Pass self class parameter python

Here is definition of my class full of static functions. I want to use all of them in "sendLog" function which call himself with time interval (10 sec here). When I run this interpreter tells me "TypeError: sendLog() takes at least 5 arguments (0 given)"
But it if I enter the same params I will need to define sendLog again and again because it calls himself repeatly.. I know its not the way But cant figure it out.
class AccessLog:
#staticmethod
def backupAccessLog(target, source):
newfile = os.path.splitext(source)[0] + "_" + time.strftime("%Y%m%d-%H%M%S") + os.path.splitext(source)[1]
copyfile(source,newfile)
shutil.move(newfile,target)
#staticmethod
def emptyAccessLog(filename):
open(filename, 'w').close()
#staticmethod
def postLogstoElastic():
fileLogs = open("example.log", "rw+")
fileBackups = open("logs_of_accesslog.log","rw+")
lines = fileLogs.read().splitlines()
logging.basicConfig(format='%(asctime)s>>>%(message)s',filename='logs_exceptions.log',level=logging.DEBUG)
es = Elasticsearch(['http://localhost:9200/'], verify_certs=True)
#es.create(index="index_log23June", doc_type="type_log23June")
es.indices.create(index='index_log23June', ignore=400)
i=0
for item in lines:
try:
i+=1
if bool(item):
es.index(index="index_log23June",doc_type="type_log23June", body={"Log":item})
else:
print "a speace line ignored. at line number:", i
raise ValueError('Error occurred on this line: ', i)
print "lines[",i,"]:",item,"\n"
except ValueError as err:
logging.error(err.args)
#staticmethod
def sendLog(interval, worker_functions, iterations=1):
def call_worker_functions():
for f in worker_functions:
f() #ERROR: Msg: 'NoneType' object is not callable
for i in range(iterations):
threading.Timer(interval * i, call_worker_functions).start()
and I want to call this method with this line:
try:
AccessLog.AccessLog.sendLog(
interval=10,
worker_functions=(
AccessLog.AccessLog.backupAccessLog("logbackups","example.log"),
AccessLog.AccessLog.emptyAccessLog("example.log"),
AccessLog.AccessLog.postLogstoElastic()
),
iterations=999
)
except ValueError as err:
logging.error(err.args)
"TypeError: sendLog() takes at least 5 arguments (0 given)" It looks normal but How can I handle this ?
Have you tried to set the #staticmethod on the same level as the function?
Apparently you want sendLog() to call the worker functions every 10 seconds or so.
Here's an easy way to do that:
class AccessLog:
#staticmethod
def sendLog(interval, worker_functions, iterations=1):
def call_worker_functions():
for f in worker_functions:
f(*worker_functions[f])
for i in range(iterations):
threading.Timer(interval * i, call_worker_functions).start()
And now use it like this:
AccessLog.AccessLog.sendLog(
interval=10,
worker_functions={
AccessLog.AccessLog.backupAccessLog: ("logbackups", "example.log"),
AccessLog.AccessLog.emptyAccessLog: ("example.log",),
AccessLog.AccessLog.postLogstoElastic: ()
),
iterations=999
)
And this is just one of many many ways, but there's no need to pass the function as its own argument like you did.

Python: TypeError: __init__() takes exactly 2 arguments (1 given)

I know this question has been asked several times, but none have managed to provide me with a solution to my issue. I read these:
__init__() takes exactly 2 arguments (1 given)?
class __init__() takes exactly 2 arguments (1 given)
All I am trying to do is create two classes for a "survival game" much like a very crappy version of minecraft. Bellow is the full code for the two classes:
class Player:
'''
Actions directly relating to the player/character.
'''
def __init__(self, name):
self.name = name
self.health = 10
self.shelter = False
def eat(self, food):
self.food = Food
if (food == 'apple'):
Food().apple()
elif (food == 'pork'):
Food().pork()
elif (food == 'beef'):
Food().beef()
elif (food == 'stew'):
Food().stew()
class Food:
'''
Available foods and their properties.
'''
player = Player()
def __init__(self):
useless = 1
Amount.apple = 0
Amount.pork = 0
Amount.beef = 0
Amount.stew = 0
class Amount:
def apple(self):
player.health += 10
def pork(self):
player.health += 20
def beef(self):
player.health += 30
def stew(self):
player.health += 25
And now for the full error:
Traceback (most recent call last):
File "/home/promitheas/Desktop/programming/python/pygame/Survive/survive_classe s.py", line 26, in <module>
class Food:
File "/home/promitheas/Desktop/programming/python/pygame/Survive/survive_classe s.py", line 30, in Food
player = Player()
TypeError: __init__() takes exactly 2 arguments (1 given)
I just want to make the classes work.
The code you used is as follows:
player = Player()
This is an issue since the __init__ must be supplied by one parameter called name according to your code. Therefore, to solve your issue, just supply a name to the Player constructor and you are all set:
player = Player('sdfasf')
The problem is that the Class Player's __init__ function accepts a name argument while you are initializing the Class instance. The first argument, self is automatically handled when you create a class instance. So you have to change
player = Player()
to
player = Player('somename')
to get the program up and running.
__init__() is the function called when the class is instantiated. So, any arguments required by __init__ need to be passed when creating an instance. So, instead of
player = Player()
use
player = Player("George")
The first argument is the implicit self, which doesn't need to be included when instantiating. name, however, is required. You were getting the error because you weren't including it.
Your code know expects that you input something in __init__ which you don't.
I have made a simple example below that does give you an idea where the error __init__() takes exactly 2 arguments (1 given) is coming from.
What I did is I made a definition where I give input to useless.
And I am calling that definition from __init__.
Example code:
class HelloWorld():
def __init__(self):
self.useThis(1)
def useThis(self, useless):
self.useless = useless
print(useless)
# Run class
HelloWorld()
If you have a definition like def exampleOne(self) it doesn't expect any input. It just looks a t itself. But def exampleTwo(self, hello, world) expects two inputs.
So to call these two you need:
self.exampleOne()
self.exampleTwo('input1', 'input2')

ERROR: unbound method "method name" must be called with "Class Name" instance as first argument (got classobj instance instead)

I hope you guys can help me out here.
I've been given this error from the following code:
Traceback (most recent call last):
File "C:\Python27\Lib\idlelib\Tarea5.py", line 60, in <module>
bg.addBandit(b)
TypeError: unbound method addBandit() must be called with BanditGroup instance as first argument (got classobj instance instead)
The code:
from numpy import *
from matplotlib import pyplot as p
class Bandit:
power = random.uniform(15,46)
life = random.uniform(40,81)
def __init__(self, power, life):
self.power = power
self.life = life
class BanditGroup:
def __init__(self,a):
self.group = [a] #Where 'a' is an object of the class Bandit
def addBandit(self,b):
self.group.append(b) #Where 'b' is an object of the class Bandit
return self.group
howmanygroups = random.randint(4,11)
i = 0
j = 0
while i <= howmanygroups:
bg = BanditGroup
howmanybandits = random.randint(1,11)
while j <= howmanybandits:
b = Bandit
bg.addBandit(b) #<-- line 60
j+=1
bgposx = random.uniform(0,50000)
bgposy = random.uniform(0,50000)
p.plot(bgposx,bgposy,'r^')
i+=1
I'd really appreciate if someone could tell me what's going on here. I started learning python 2.7 about 2 months ago.
Thanks!
Try changing your code to (notice the parenthesis around class instantiation):
while i <= howmanygroups:
bg = BanditGroup(a)
howmanybandits = random.randint(1,11)
while j <= howmanybandits:
b = Bandit(power, life)
bg.addBandit(b) #<-- line 60
The problem is that addBandit requires an instance of BanditGroup to be used. Adding (...) after the class name will create one:
bg = BanditGroup(...)
Right now, you have bg pointing to the class itself, not an instance of it.
The same thing needs to be done here with Bandit:
b = Bandit(...)
Note: ... means to pass in the appropriate arguments. You made BanditGroup.__init__ with a required a parameter and Bandit.__init__ with required power and life parameters. Since I don't know what you want these to be, I left them out.
Yes probably need parens when you create an instance of your Bandit and BanditGroup classes. Otherwise, you're assigning a class to your variables, not an instance of a class.
EG: bg = BanditGroup()

Categories

Resources