Sorry if this question is stupid. I created an unittest class which needs to take given inputs and outputs from outside. Thus, I guess these values should be initiated. However, I met some errors in the following code:
CODE:
import unittest
from StringIO import StringIO
##########Inputs and outputs from outside#######
a=[1,2]
b=[2,3]
out=[3,4]
####################################
def func1(a,b):
return a+b
class MyTestCase(unittest.TestCase):
def __init__(self,a,b,out):
self.a=a
self.b=b
self.out=out
def testMsed(self):
for i in range(self.tot_iter):
print i
fun = func1(self.a[i],self.b[i])
value = self.out[i]
testFailureMessage = "Test of function name: %s iteration: %i expected: %i != calculated: %i" % ("func1",i,value,fun)
self.assertEqual(round(fun,3),round(value,3),testFailureMessage)
if __name__ == '__main__':
f = MyTestCase(a,b,out)
from pprint import pprint
stream = StringIO()
runner = unittest.TextTestRunner(stream=stream, verbosity=2)
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
print 'Tests run', result.testsRun
However, I got the following error
Traceback (most recent call last):
File "C:testing.py", line 33, in <module>
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
File "C:\Python27\lib\unittest\loader.py", line 310, in makeSuite
return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
File "C:\Python27\lib\unittest\loader.py", line 50, in loadTestsFromTestCase
if issubclass(testCaseClass, suite.TestSuite):
TypeError: issubclass() arg 1 must be a class
Can anyone give me some suggestions? Thanks!
The root of the problem is this line,
result = runner.run(unittest.makeSuite(MyTestCase(a,b,out)))
unittest.makeSuite expects a class, not an instance of a class. So just MyTestCase, not MyTestCase(a, b, out). This means that you can't pass parameters to your test case in the manner you are attempting to. You should probably move the code from init to a setUp function. Either access a, b, and out as globals inside setUp or take a look at this link for information regarding passing parameters to a unit test.
By the way, here is the source file within python where the problem originated. Might be informative to read.
Related
I'm trying to call a method from a class that is in a different file. This is how my code looks:
main.py
###Imports
import funct as f
import schedule
import time
###More Imports
###Grabbing GPS data from user and assigning values
bboxsize = f.find(userLat, userLng, userRad)
if __name__ == '__main__':
r = f.find.radar(bboxsize) ### <---- Line 14
schedule.every(5).seconds.do(r)
while True:
schedule.run_pending()
time.sleep(1)
funct.py
###Imports
class find:
def __init__(self, userLat, userLng, userRad):
self.userLat = userLat
self.userLng = userLng
self.userRad = userRad
def bboxFormula(self):
### Lots of code that is not important to this
return bboxsize
def radar(self, bboxsize):
api = OpenSkyApi(username='###', password='###')
states = api.get_states(bbox=bboxsize)
print(f"vvvvvv| {time.ctime(time.time())} |vvvvvv")
print("------------------------------------------")
for s in states.states:
print("Callsign: %r, Latitude: %r, Longitude: %r, Altitude (meters): %r, Velocity %r)" % (s.callsign, s.latitude, s.longitude, s.geo_altitude, s.velocity))
print("------------------------------------------")
When running this I get:
Traceback (most recent call last):
File "/##/##/##/##/main.py", line 14, in <module>
r = f.find.radar(bboxsize)
TypeError: find.radar() missing 1 required positional argument: 'bboxsize'
I can run all of this in one file without classes, so I know it works. I have been messing with this for a while getting all sorts of errors with every change I make.
Is there something that I'm missing or is there no way for me to do this with the Schedule Module?
I’m just guessing here, but I think you had different code when it was all one file.
Now with two files I think you meant to write this:
find = f.find(userLat, userLng, userRad)
boxsize = find.bboxFormula()
if __name__ == '__main__':
r = lambda :find.radar(bboxsize) ### <---- Line 14
schedule.every(5).seconds.do(r)
while True:
schedule.run_pending()
time.sleep(1)
I'm using Zipline-1.1.1, Python3.4.6 to create a dynamic stock selector as follows:
from zipline.pipeline import Pipeline, engine
from zipline.pipeline.factors import AverageDollarVolume, Returns
def make_pipeline():
dollar_volume = AverageDollarVolume(window_length=1)
high_dollar_volume = dollar_volume.percentile_between(N, 100)
recent_returns = Returns(window_length=N, mask=high_dollar_volume)
low_returns = recent_returns.percentile_between(0, n)
high_returns = recent_returns.percentile_between(N, 100)
pipe_columns = {
'low_returns': low_returns,
'high_returns': high_returns,
'recent_returns': recent_returns,
'dollar_volume': dollar_volume
}
pipe_screen = (low_returns | high_returns)
pipe = Pipeline(columns=pipe_columns, screen=pipe_screen)
return pipe
I initialize a pipeline object with:
my_pipe = make_pipeline()
But when I try to populate the Pipeline, it fails with:
result = engine.PipelineEngine.run_pipeline(my_pipe, '2017-07-10', '2017-07-11')
Traceback (most recent call last):
File "<input>", line 1, in <module>
result = engine.PipelineEngine.run_pipeline(my_pipe, '2017-07-10', '2017-07-11')
TypeError: run_pipeline() missing 1 required positional argument: 'end_date'
I can't figure out what is wrong, any help is much appreciated.
If I understand correctly, you're using this library.
As far as I can see from that code, to be able to use run_pipeline method you have to instantiate on of pipeline engines before, e.g. SimplePipelineEngine. You need that because PipelineEngine is a class, even abstract class, not an object.
So you have to create an object of SimplePipelineEngine class and then call run_pipeline on it. You can do it this way:
your_engine = SimplePipelineEngine(get_loader=your_loader, calendar=your_calendar, asset_finder=your_asset_finder)
your_eninge.run_pipeline(my_pipe, '2017-07-10', '2017-07-11')
Of course you have to create your_loader etc. first.
Here is example of SimplePipelineEngine usage. I hope it will help.
I'm working on a project and this error keeps showing up:
class PRNG:
def __init__(self):
# parameters
# P-256 prime
self.p=115792089210356248762697446949407573530086143415290314195533631308867097853951
self.a=self.p-3
self.b=41058363725152142129326129780047268409114441015993725554835256314039467401291
self.E=curve(self.a,self.b,self.p)
self.E.n=115792089210356248762697446949407573529996955224135760342422259061068512044369
self.P=point(0,46263761741508638697010950048709651021688891777877937875096931459006746039284)
self.k=183521403747637560534595403690771364941493702673414885451510208165414833985
self.Q=mult(self.k,self.P,self.E)
self.t=bytes_to_int(os.urandom(32)) # initial seed
#print self.t
self.output_length=240
self.truncate_length=16
def function_attack(self, nbytes, predicted_state):
calls = ((nbytes*8-1)/self.output_length)+1
out = ''
for i in xrange(calls):
tP=mult(predicted_state,self.P,self.E)
s=tP.x
sQ=mult(s,self.Q,self.E)
r=sQ.x
r_out=r % (2**self.output_length)
self.t=s
out = out + int_to_bytes(r_out, self.output_length/8)
return out[:nbytes]
def function(self, nbytes):
calls = ((nbytes*8-1)/self.output_length)+1
out = ''
for i in xrange(calls):
tP=mult(self.t,self.P,self.E)
s=tP.x
sQ=mult(s,self.Q,self.E)
r=sQ.x
r_out=r % (2**self.output_length)
self.t=s
out = out + int_to_bytes(r_out, self.output_length/8)
return out[:nbytes]
The first method is being called in a separate file and the output is always the following(regardless if I change the name of the local variable calls):
File "C:\file1.py", line 32, in <module>
prng = PRNG()
File "C:\file_where_error_occurs.py", line 286, in __init__
for i in xrange(calls):
NameError: global name 'calls' is not defined
What is python doing?
you have indentation errors ... this is typically caused by mixing tabs and spaces ... most decent editors can fix this for you easily ... to see your indentation errors run your program as
python -tt my_program.py
I have two functions which print into an excel file. THe only input is the file name. Here is the code:
#excelpy
import excelpy
#Tinker
from Tkinter import *
from tkSimpleDialog import *
from tkFileDialog import *
Function Mode1
def Mode1(full_name):
print full_name
print type(full_name)
testwbook = excelpy.workbook(full_name)
testwbook.show()
testwbook.set_cell((1,1),'TEST1', fontColor='red')
testwbook.set_range(2,1,['Number','Name'])
m1 = testwbook.save(full_name)
testwbook.close()
return m1
Function Mode2
def Mode2(full_name):
print full_name
print type(full_name)
testwbook = excelpy.workbook(full_name)
testwbook.show()
testwbook.set_cell((1,1),'TEST2', fontColor='red')
testwbook.set_range(2,1,['Number','Name'])
m2 = testwbook.save(full_name)
testwbook.close()
return m2
Main
root = Tk()
d = str(asksaveasfilename(parent=root,filetypes=[('Excel','*.xls')],title="Save report as..."))
d = d + '.xls'
d = d.replace('/','\\')
root.destroy()
Mode1(d)
Mode2(d)
And once in a while I get the following error:
Traceback (most recent call last):
File "T:\TEST\testpy.py", line 2035, in <module>
Mode2(d)
File ""T:\TEST\testpy.py"", line 1381, in Mode2
print type(full_name)
TypeError: 'str' object is not callable
Any idea why is this happening? How can I prevent it?
The only function call in the line you get the error is a call to the built-in function type(), so the only explanation for your error message is that you overwrote the built-in name type by a global name type pointing to a string object. Try adding
print type
before
print type(full_name)
It looks like somewhere you're setting a (global) variable named type to a string, thus overwriting the built-in type function.
Try searching your code for type = to see what turns up.
Understandably, Python would then throw that exception when you tried to call type (strings can't be "called").
I'm playing with contract.py, Terrence Way's reference implementation of design-by-contract for Python. The implementation throws an exception when a contract (precondition/postcondition/invariant) is violated, but it doesn't provide you a quick way of identifying which specific contract has failed if there are multiple ones associated with a method.
For example, if I take the circbuf.py example, and violate the precondition by passing in a negative argument, like so:
circbuf(-5)
Then I get a traceback that looks like this:
Traceback (most recent call last):
File "circbuf.py", line 115, in <module>
circbuf(-5)
File "<string>", line 3, in __assert_circbuf___init___chk
File "build/bdist.macosx-10.5-i386/egg/contract.py", line 1204, in call_constructor_all
File "build/bdist.macosx-10.5-i386/egg/contract.py", line 1293, in _method_call_all
File "build/bdist.macosx-10.5-i386/egg/contract.py", line 1332, in _call_all
File "build/bdist.macosx-10.5-i386/egg/contract.py", line 1371, in _check_preconditions
contract.PreconditionViolationError: ('__main__.circbuf.__init__', 4)
My hunch is that the second argument in the PreconditionViolationError (4) refers to the line number in the circbuf.init docstring that contains the assertion:
def __init__(self, leng):
"""Construct an empty circular buffer.
pre::
leng > 0
post[self]::
self.is_empty() and len(self.buf) == leng
"""
However, it's a pain to have to open the file and count the docstring line numbers. Does anybody have a quicker solution for identifying which contract has failed?
(Note that in this example, there's a single precondition, so it's obvious, but multiple preconditions are possible).
This is an old question but I may as well answer it. I added some output, you'll see it at the comment # jlr001. Add the line below to your contract.py and when it raises an exception it will show the doc line number and the statement that triggered it. Nothing more than that, but it will at least stop you from needing to guess which condition triggered it.
def _define_checker(name, args, contract, path):
"""Define a function that does contract assertion checking.
args is a string argument declaration (ex: 'a, b, c = 1, *va, **ka')
contract is an element of the contracts list returned by parse_docstring
module is the containing module (not parent class)
Returns the newly-defined function.
pre::
isstring(name)
isstring(args)
contract[0] in _CONTRACTS
len(contract[2]) > 0
post::
isinstance(__return__, FunctionType)
__return__.__name__ == name
"""
output = StringIO()
output.write('def %s(%s):\n' % (name, args))
# ttw001... raise new exception classes
ex = _EXCEPTIONS.get(contract[0], 'ContractViolationError')
output.write('\tfrom %s import forall, exists, implies, %s\n' % \
(MODULE, ex))
loc = '.'.join([x.__name__ for x in path])
for c in contract[2]:
output.write('\tif not (')
output.write(c[0])
# jlr001: adding conidition statement to output message, easier debugging
output.write('): raise %s("%s", %u, "%s")\n' % (ex, loc, c[1], c[0]))
# ...ttw001
# ttw016: return True for superclasses to use in preconditions
output.write('\treturn True')
# ...ttw016
return _define(name, output.getvalue(), path[0])
Without modifying his code, I don't think you can, but since this is python...
If you look for where he raises the exception to the user, it I think is possible to push the info you're looking for into it... I wouldn't expect you to be able to get the trace-back to be any better though because the code is actually contained in a comment block and then processed.
The code is pretty complicated, but this might be a block to look at - maybe if you dump out some of the args you can figure out whats going on...
def _check_preconditions(a, func, va, ka):
# ttw006: correctly weaken pre-conditions...
# ab002: Avoid generating AttributeError exceptions...
if hasattr(func, '__assert_pre'):
try:
func.__assert_pre(*va, **ka)
except PreconditionViolationError, args:
# if the pre-conditions fail, *all* super-preconditions
# must fail too, otherwise
for f in a:
if f is not func and hasattr(f, '__assert_pre'):
f.__assert_pre(*va, **ka)
raise InvalidPreconditionError(args)
# rr001: raise original PreconditionViolationError, not
# inner AttributeError...
# raise
raise args
# ...rr001
# ...ab002
# ...ttw006