Python 2.7 assertin gets error object has no attribute - assert

I have Python 2.7.5 on my system python --version
I have a basic script that tries to verify something and assert if false. Here is the simple test I created that is failing.
Note Early on Asserts (pre 2.7) works fine.
import unittest
class TestSuite (unittest.TestCase):
def test002_last_Chat(self):
logger.info("This will select the chat with the user who we cleared. .")
a.selectMenu('Start a Chat')
self.assertEqual("im", "im") #This assert works fine
self.assertIn ("a", "apple") #FAILS
self.assertIn ("a", "pple") #FAILS
logger.info ("test01")\
if __name__ == '__main__':
logger.info("Running test: "+scriptName)
a = IPHONE()
b = BROWSER()
c = SAWS()
myTest = TestSuiteRunner(TestSuite, scriptName, testDescription, device=device)
myTest.runtest()
I get this error when I run it
Test complete (ERROR): test002_last_Chat (__main__.TestSuite)
(<type 'exceptions.AttributeError'>, AttributeError("'TestSuite' object has no attribute 'assertIn'",), <traceback object at 0x3>)
Traceback (most recent call last):
File "/Users/drlazor/Documents/AIM/6-17/oscar/qa/clients/TRAVOLTA/scripts_iphone/iphoneAIM_close.sikuli/iphoneAIM_close.py", line 194, in test002_last_Chat
self.assertIn ("a", "apple")
AttributeError: 'TestSuite' object has no attribute 'assertIn'
I am using this documentation http://docs.python.org/2/library/unittest.html#assert-methods as a guide.

There seems to be an issue with assertIn in some versions of Python. Here's an alternative that should work:
a = 'a'
apple = 'apple'
self.assertTrue(a in apple, '{} not in {}'.format(a, apple))

Related

Why isn't call_command( ... stdout=f ) intercepting stdout? At my wits end

Help! I am unable to get testing for my management command to work. The command works fine when tested manually:
$ ./manage.py import_stock stock/tests/header_only.csv
Descriptions: 0 found, 0 not found, 0 not unique
StockLines: 0 found, 0 not found, 0 not unique
but not in a test. It's outputting to stdout despite call_command specifying stdout=f (f is a StringIO()). Running the test, I get
$ ./manage.py test stock/tests --keepdb
Using existing test database for alias 'default'...
System check identified no issues (0 silenced).
Descriptions: 0 found, 0 not found, 0 not unique
StockLines: 0 found, 0 not found, 0 not unique
Returned
""
F
======================================================================
FAIL: test_001_invocation (test_import_stock_mgmt_cmd.Test_010_import_stock)
make sure I've got the basic testing framework right!
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/nigel/django/sarah/silsondb/stock/tests/test_import_stock_mgmt_cmd.py",line 32, in test_001_invocation
self.assertIn('Descriptions: 0', text) # do-nothing
AssertionError: 'Descriptions: 0' not found in ''
----------------------------------------------------------------------
Ran 1 test in 0.006s
FAILED (failures=1)
Preserving test database for alias 'default'...
The test code which generates this is as follows. print(f'Returned\n"{text}"') shows that I'm getting a null string back from do_command (which creates the StringIO() and invokes call_command ). What I'm trying to intercept is being written to the console, just as when I invoke the command directly.
import csv
import io
from django.core.management import call_command
from django.core.management.base import CommandError
from django.test import TestCase
class Test_010_import_stock( TestCase):
def do_command( self, *args, **kwargs):
with io.StringIO() as f:
call_command( *args, stdout=f )
return f.getvalue()
def test_001_invocation(self):
""" make sure I've got the basic testing framework right! """
text = self.do_command( 'import_stock', 'stock/tests/header_only.csv')
print(f'Returned\n"{text}"')
print()
self.assertIn('Descriptions: 0', text) # do-nothing
self.assertIn('Stocklines: 0', text )
Answering own question. It was a silly bit of confusion in the management command itself.
I knew you didn't use print but should use self.stdout.write() in a management command
But a braino resulted in sys.stdout.write and by sheer bad luck, this particular command was importing sys. It's been one of those mornings.

Python: Problem with logging.error(traceback.format_exception)

I have following code:
def tearDown(self):
e_type, e_value, tb = sys.exc_info()
if e_type is not None:
logging.error((traceback.format_exception(e_type, e_value, tb)))
when I used Python 2.7 everything works fine, but after upgrade to version 3.6 it doesn't work anymore:
For example I have created some example for testing and I expect error.
def test_create_new_user_without_all_fields1(self):
self.assertEqual('USER_1', 'USER_2')
logging.info('test_create_new_user_without_all_fields1: Passed')
Result in console:
======================================================================
FAIL: test_create_new_user_without_all_fields1 (test_testExample.BaseTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Dev\git\CST\tests\test_testExample.py", line 16, in test_create_new_user_without_all_fields1
self.assertEqual('USER_1', 'USER_2')
AssertionError: 'USER_1' != 'USER_2'
- USER_1
+ USER_2
? +
lets add small print to tearDown:
print (sys.exc_info())
Result:
(None, None, None)
As can we see there is no exceptions anymore, but should be. How to fix this problem ?
e_type, e_value, tb = self._outcome.errors[1][1]
logging.error(''.join(traceback.format_exception(e_type, e_value, tb)))

'Wit' object has no attribute 'message'

Just trying to experiment with Wit.ai & Python but getting the following error. What am I doing wrong here??
Error:
Traceback (most recent call last):
File "C:/Python27/mx1.py", line 7, in <module>
resp = client.message(my_message)
AttributeError: 'Wit' object has no attribute 'message'
Code:
from wit import Wit
access_token='B3GHXHLTXIASO7S4KY7UC65LMSTCDEHK'
client = Wit(access_token)
my_message='who are you?'
resp = client.message(my_message)
print(resp)
So, it seems like you're using an older (actually unofficial) version of the Python pywit package, last updated on 2015-11-07 (version 0.4.0).
You should remove the pywit package and install wit, just like they say in the docs/install section:
pip uninstall pywit
pip install wit
Just for completeness, if you look inside the wit.py of your older pywit package, inside your python2.7/site-packages/wit/wit.py, you'll see the definition of old Wit class, with a get_message() method instead of the current message(). So, in the pywit, your code will run if you say:
resp = client.get_message(my_message)
instead of
resp = client.message(my_message)
But you should really switch to the current (official) version.

AttributeError: TestSwitch instance has no attribute 'assertTrue'

I have a following pyunit test case code where I am collecting the result of the function (True or False) and using it to drive my assertion. However, I am getting the "no attribute" error for assertTrue. What is missing here?
I am using python 2.7.8 and pyunit version of PyUnit-1.4.1-py2.7.
The same code when run from the Eclipse (pydev plugin) from my Mac, it works fine. Only when I take this to my Linux box, it does throw below error. So to me it looks like some package incompatibility problem.
import json
import unittest
class TestSwitch(unittest.TestCase):
def testFunction(self):
self.assertTrue(True, "test case failed")
Below is the test suite class.
import unittest
from mysample import TestSwitch
# Create an instance of each test case.
testCase = TestSwitch('testFunction')
# Add test cases to the test suite.
testSuite = unittest.TestSuite()
testSuite.addTest(testCase)
# Execute the test suite.
testRunner = unittest.TextTestRunner(verbosity=2)
testRunner.run(testSuite)
It throws below error.
bash-3.2$ python mysuite.py
testFunction (mysample.TestSwitch) ... ERROR
======================================================================
ERROR: testFunction (mysample.TestSwitch)
----------------------------------------------------------------------
Traceback (most recent call last):
File "workspace/pyunit/mysample.py", line 7, in testFunction
self.assertTrue(True, "test case failed")
AttributeError: TestSwitch instance has no attribute 'assertTrue'
----------------------------------------------------------------------
Ran 1 tests in 0.000s
FAILED (errors=1)
bash-3.2$
For now I've figured a workaround for this problem by using 'assertEqual' comparing with a boolean value and it works. I am not sure why 'assertTrue' and for that matter 'assertFalse' is having problem. I did not change any package version or anything.
The workaround code is as below.
17 def testFunction(self):
18 res = True
19 self.assertEqual(res, True, 'test case failed')

Encountering remote error using grpc with protobuf2.6 in python

I am using grpc with protobuf 2.6.1 in python 2.7, and when I run my client side code, I have the following errors:
Traceback (most recent call last):
File "debate_client.py", line 31, in <module>
run_client()
File "debate_client.py", line 17, in run_client
reply = stub.Answer(debate_pb2.AnswerRequest(question=question, timeout=timeout), 30)
File "/Users/elaine/Desktop/gitHub/grpc/python2.7_virtual_environment/lib/python2.7/site-packages/grpc/framework/crust/implementations.py", line 73, in __call__
protocol_options, metadata, request)
File "/Users/elaine/Desktop/gitHub/grpc/python2.7_virtual_environment/lib/python2.7/site-packages/grpc/framework/crust/_calls.py", line 109, in blocking_unary_unary
return next(rendezvous)
File "/Users/elaine/Desktop/gitHub/grpc/python2.7_virtual_environment/lib/python2.7/site-packages/grpc/framework/crust/_control.py", line 412, in next
raise self._termination.abortion_error
grpc.framework.interfaces.face.face.RemoteError: RemoteError(code=StatusCode.UNKNOWN, details="")
Here is my client side code:
from grpc.beta import implementations
import debate_pb2
import sys
def run_client():
params = sys.argv
print params
how = params[1]
question = params[2]
channel = implementations.insecure_channel('localhost', 29999)
stub = debate_pb2.beta_create_Candidate_stub(channel)
if how.lower() == "answer":
timeout = int(params[3])
reply = stub.Answer(debate_pb2.AnswerRequest(question=question, timeout=timeout), 30)
elif how.lower() == "elaborate":
blah = params[3:len(sys.argv)]
for i in range(0, len(blah)):
blah[i] = int(blah[i])
reply = stub.Elaborate(debate_pb2.ElaborateRequest(topic=question, blah_run=blah), 30)
if reply is None:
print "No comment"
else:
print reply.answer
if __name__ == "__main__":
run_client()
And here is my server side code:
import debate_pb2
import consultation_pb2
import re
import random
from grpc.beta import implementations
class Debate(debate_pb2.BetaCandidateServicer):
def Answer(self, request, context=None):
#Answer implementation
def Elaborate(self, request, context=None):
#Elaborate implementation
def run_server():
server = debate_pb2.beta_create_Candidate_server(Debate())
server.add_insecure_port('localhost:29999')
server.start()
if __name__ == "__main__":
run_server()
Any idea where the remote error comes from? Thank you so much!
Hello Elaine and thank you for trying out gRPC Python.
Nothing leaps out at me as an obvious smoking gun, but a couple of things I see are:
gRPC Python isn't known to work with protobuf 2.6.1. Have you tried working with the very latest protobuf release (3.0.0a3 at this time)?
context isn't an optional keyword parameter in servicer methods; it's a required, positional parameter. Does dropping =None from your servicer method implementations effect any change?
The same happened to me just now, and I figured out why.
Make sure the messages in your proto definition and the message in your implementations match the format.
For example, my Response message had a message= param in my python server, but not in my proto definition.
I think your function implementations should be outside class Debate or might be your functions are not correctly implemented to give the desired result.
I faced a similar error because my functions were inside the class but moving it outside the class fixed it.