how to test whether program exits or not - testing

I want to test the next class:
from random import randint
class End(object):
def __init__(self):
self.quips=['You dead', 'You broke everything you can','You turn you head off']
def play(self):
print self.quips[randint(0, len(self.quips)-1)]
exit(1)
I want to test it with nosetests so I could see that the class exits correctly with code 1. I tried differents variants but nosetest returns error like
File "C:\Python27\lib\site.py", line 372, in __call__
raise SystemExit(code)
SystemExit: 1
----------------------------------------------------------------------
Ran 1 test in 5.297s
FAILED (errors=1)
Ofcourse I can assume that it exits but I want for test to return OK status not error. Sorry if my question may be stupid. Im very new to python and I try to test something my very first time.

I would recommend using the assertRaises context manager. Here is an example test that ensures that the play() method exits:
import unittest
import end
class TestEnd(unittest.TestCase):
def testPlayExits(self):
"""Test that the play method exits."""
ender = end.End()
with self.assertRaises(SystemExit) as exitexception:
ender.play()
# Check for the requested exit code.
self.assertEqual(exitexception.code, 1)

As you can see in the traceback, sys.exit()* raises an exception called SystemExit when you call it. So, that's what you want to test for with nose's assert_raises(). If you are writing tests with unittest2.TestCase that's self.assertRaises.
*actually you used plain built-in exit() but you really should use sys.exit() in a program.

Related

How to close a QInputDialog with after a defined amount of time

I'm currently working on an application that run in the background and sometime create an input dialog for the user to answer. If the user doesn't interact, I'd like to close the dialog after 30 seconds. I made a QThread that act like a timer and the "finished" signal should close the dialog. I unfortunately cannot find a way to close it.
At this point I'm pretty much lost. I completely new to QThread and a beginner in PyQt5
Here is a simplified version of the code (we are inside a class running a UI):
def Myfunction(self,q):
# q : [q1,q2,q3]
self.popup = counter_thread()
self.popup.start()
self.dial = QInputDialog
self.popup.finished.connect(self.dial.close)
text, ok = self.dial.getText(self, 'Time to compute !', '%s %s %s = ?'%(q[0], q[2], q[1]))
#[...]
I tried ".close()" and others but i got this error message:
TypeError: close(self): first argument of unbound method must have type 'QWidget'
I did it in a separated function but got the same problem...
You cannot close it because the self.dial you created is just an alias (another reference) to a class, not an instance.
Also, getText() is a static function that internally creates the dialog instance, and you have no access to it.
While it is possible to get that dialog through some tricks (installing an event filter on the QApplication), there's no point in complicating things: instead of using the static function, create a full instance of QInputDialog.
def Myfunction(self,q):
# q : [q1,q2,q3]
self.popup = counter_thread()
self.dial = QInputDialog(self) # <- this is an instance!
self.dial.setInputMode(QInputDialog.TextInput)
self.dial.setWindowTitle('Time to compute !')
self.dial.setLabelText('%s %s %s = ?'%(q[0], q[2], q[1]))
self.popup.finished.connect(self.dial.reject)
self.popup.start()
if self.dial.exec():
text = self.dial.textValue()
Note that I started the thread just before showing the dialog, in the rare case it may return immediately, and also because, for the same reason, the signal should be connected before starting it.

I got TypeError: getMboSet(): expected 2-4 args; got 1 in <script> while using MAXIMO Automation Script

I'm developing an automation script and I'm getting the next error:
BMXAA7837E - An error occured that prevented the BAX_ISSUEGL script for the BAX_ISSUEGL launch point from running.
TypeError: getMboSet(): expected 2-4 args; got 1 in at line number 5 More information
I'm using jython 2.5.2, MAXIMO 7.6.0.9. The automation is an Object Launch Point automation.
Someone knows why I'm getting the error?
The automation script:
from psdi.mbo import Mbo
from psdi.mbo import MboConstants
#Get object
issueCI = Mbo.getMboSet("ISSUECURRENTITEM")
#Get Storeloc and Accounts
storeloc=issueCI.getString("STORELOC");
debitacct=issueCI.getString("GLDEBITACCT");
if debitacct[0:4] != storeloc:
errorgroup= "Credit Error";
errorkey= "CreditError";
The problem with line 5 is that you have capitalized Mbo -- suggesting you're referring to the class psdi.mbo.Mbo that you imported. But the launch point will pass an implicit variable called mbo to your script, and mbo will be an instance of (a subclass of) Mbo.
Python methods are functions in classes, and they take self as the first parameter. So, in mbo.getMboSet("RELATIONSHIPNAME"), Python is going to internally convert that getMboSet(mbo, "RELATIONSHIPNAME"). By referencing the class instead of an instance of the class, you were actually leaving out that self parameter. And this is why you were told that getMboSet() was expecting "2-4 arguments" when the JavaDocs for Mbo.getMboSet() show overloads of that method that take 1, 2 or 3 arguments.
FYI: For the code you pasted, once you change Mbo to mbo on line 5, you don't need any of your from ... import lines. You only need those if you directly reference the classes, like line 5 was doing in error.

Robotframework - get failing keyword / stack trace of failure

I have a keyword called "debug teardown" which prints the test status and then runs the debuglibrary Debug keyword, if the test has failed.
I would like to be able to log to console which keyword has caused the failure, so I can more effectively debug my test.
Is it possible to get the stack trace or most recent test keyword, and log it to the console?
Here is my Debug Teardown keyword:
Debug Teardown
Run Keyword If Test Failed Log ${TEST STATUS}: ${TEST MESSAGE} ERROR
Run Keyword If Test Failed Debug
You can get a bit more information if you create a listener and also set the log level to DEBUG. Inside the listener you can save the results of log commands, and then when a keyword fails you can print it out or do whatever else you want.
For example, here's a listener that will print to stdout the last log message when a keyword fails:
from __future__ import print_function
class my_listener():
ROBOT_LISTENER_API_VERSION = 2
def __init__(self):
self.ROBOT_LIBRARY_LISTENER = self
self.last_log = None
def _log_message(self, message):
self.last_log = message
def _end_keyword(self, name, attrs):
if attrs['status'] == 'FAIL':
print("\n******\n", self.last_log['message'])
You would use it by importing the listener like a normal library, and also setting the log level to DEBUG (otherwise you'll get the error but no stack trace).
Example:
*** Settings ***
Library my_listener
Suite Setup set log level DEBUG
*** Test cases ***
Example
some keyword
You might be able to utilize set suite variable to update a "global" variable as you go. The last set variable value would be the value that failed.

what does greenthread.sleep do?

I'm pretty new with eventlet and have some questions on sleep()
I tested with a small piece of code.
At first I spawned 3 greenthreads and then called greenthread.sleep(0), then these 3 greenthreads all came to execute the functions in them. what's going on?
does sleep() mean execute all the greenthread spawned? what does the argument 0 we passed in mean?
Here is the code:
import eventlet
from eventlet import greenthread
from eventlet import event
evt = event.Event()
def func1():
print "starting func1"
evt.wait()
print "stopping func1"
def func2():
print "starting func2"
evt.wait()
print "stopping func2"
def func3():
evt.send()
gt1 = greenthread.spawn(func1)
gt2 = greenthread.spawn(func2)
gt3 = greenthread.spawn(func3)
greenthread.sleep(0)
That's a great question, it deserves a special place in Eventlet documentation.
eventlet.sleep(0) reschedules the calling greenthread to the end of run queue. If there were any other greenthreads waiting to run, they will execute now.
Current implementation detail of Eventlet has a certain guarantee that if you call sleep, the calling greenthread will not continue until all other greenthreads that are ready to execute are finished or came to similar wait state. Started as implementation detail, we keep it as a public API now: call sleep(0) to let others run.

How to have a run script with display_trace() in it for debug purposes

I have a typical sort of "run" script (below).
When I want to debug the scenario, I use VLAB GUI ... and in this instance I want the trace window open, so I have display_trace() at the end of the run script.
However, often I just want to run this scenario in batch as part of a regression test. The problem is that VLAB throws an exception on display_trace() when in batch mode.
I don't really like the idea of
try:
display_trace()
except:
pass
(or even catching the specific error that is thrown) ... it just feels "messy". What if there is a valid exception upon display_trace() that I miss?
Is there some way not to call display_trace() at all if I'm in batch mode?
run script:
from vlab import *
import os
image_path = os.path.join('o5e', 'bin','o5e_dbg.elf')
load('ecu.sim', args=['--testbench=testbench_o5e',"--image=%s" % image_path] + __args__)
# First set up MMU
add_sw_execute_breakpoint(get_address("BamExit"))
run(blocking=True)
# Then we can set breakpoints in user code space
add_sw_execute_breakpoint(get_address("init_variables"))
run(blocking=True)
# Trace stuff
vtf_sink = trace.sink.vtf("o5e.vtf")
add_trace("+src:ecu.core_system.Core0.InstrTraceMsg", sink=vtf_sink)
add_trace(get_ports("ecu.core_system.Core0", kind="bus"), sink=vtf_sink)
display_trace(vtf_sink)
The "interface_mode" session property can be used to query whether VLAB was launched in "graphical" mode, where the VLAB IDE is displayed, or in "text" mode.
You could use this property to conditionally call vlab.display_trace():
in_graphical_mode = vlab.get_properties()["interface_mode"] == "graphical"
if in_graphical_mode:
vlab.display_trace()