Error in software unit testing simple program? - python-3.x

Testcode.py
import code
import unittest
class TestCode( unittest.TestCase ):
def test_simple( self ):
self.assertEqual( code.return_zero(),0 )
if __name__ == '__main__':
unittest.main()
code.py
def return_zero ():
return 0
expected ok result
but getting this below error
-----------------------------
Traceback (most recent call last):
File "C:++++++/.spyder-py3/testcode.py", line 6, in test_simple
self.assertEqual( code.return_zero(),0 )
AttributeError: 'Testcode' object has no attribute 'assertnotEqual'
----------------------------------------------------------------------
Ran 2 tests in 0.002s
FAILED (errors=2)

I don't understand how your code has output this error.
you need to import the return_code from the code module.
from:
import code
to:
from code import return_code
or:
from code import *
and then:
self.assertEqual(return_zero(),0 )

Related

ModuleNotFoundError: No module named in PyCharm

I was able to run the project using the command line, but from last 1 day I am not able to run the command from the command line However using GUI the project is running fine...
C:\Users\tester\PycharmProjects\Selenium\SampleProjects\POMProjectDemo\Tests>py
thon login.py
Traceback (most recent call last):
File "login.py", line 6, in <module>
from SampleProjects.POMProjectDemo.Pages.loginPage import LoginPage
ModuleNotFoundError: No module named 'SampleProjects'
C:\Users\tester\PycharmProjects\Selenium\SampleProjects\POMProjectDemo\Tests>py
thon -m unittest login.py
E
======================================================================
ERROR: login (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: login
Traceback (most recent call last):
File "C:\Users\tester\AppData\Local\Programs\Python\Python37-32\lib\unittest\
loader.py", line 154, in loadTestsFromName
module = __import__(module_name)
File "C:\Users\tester\PycharmProjects\Selenium\SampleProjects\POMProjectDemo\
Tests\login.py", line 6, in <module>
from SampleProjects.POMProjectDemo.Pages.loginPage import LoginPage
ModuleNotFoundError: No module named 'SampleProjects'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
[![Tests/login.py
import time
from selenium import webdriver
import unittest
from selenium.common.exceptions import NoSuchElementException
from SampleProjects.POMProjectDemo.Pages.loginPage import LoginPage
from SampleProjects.POMProjectDemo.Pages.homePage import HomePage
import HtmlTestRunner
from SampleProjects.POMProjectDemo.Utility.XLUtil import getData
class LoginTest(unittest.TestCase):
#classmethod
def setUpClass(cls):
cls.driver = webdriver.Chrome(executable_path='F:/Selenium/chromedriver.exe')
cls.driver.implicitly_wait(10)
cls.driver.maximize_window()
def test_login_valid(self):
path = 'c:/Users/mahmood/PycharmProjects/Selenium_automaton/Login.xlsx'
# global path
driver = self.driver
row = getData.getRowCount(path,'Sheet1')
for r in range(2,row+1):
driver.get("https://opensource-demo.orangehrmlive.com/")
userN = getData.readData(path,'Sheet1',r,1)
passW = getData.readData(path,'Sheet1',r,2)
Same code was running fine, what changes I have done not able to debug it.

import custom logging module throws error

I test following code to understand importing a custom python program and it works fine but when follow same process for importing custom logging module I see error.
Below works fine
#calculation.py
from mult import product
def add(a,b):
return a + b
if __name__== '__main__':
a = 10
b = 5
print(add(a,b))
print(product(a,b))
Now second program mult.py
# mult.py
def product(a,b):
return a * b
Below does not work, why?
#test_logger.py
import loggerforhousing
print("custom logs")
logger.info("this is info")
logger.error("this is error")
second program
#loggerforhousing.py
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s')
file_handler = logging.FileHandler('train_123.log') # store log files in artifacts directory
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
Error message
Traceback (most recent call last):
File "test_logger.py", line 3, in <module>
logger.info("this is info")
NameError: name 'logger' is not defined
Please help me figure out what I am missing.
In test_logger.py, declare logger as being part of loggerforhousing.py:
loggerforhousing.logger.info(“this is info”)
Or import logger explicitly (as done in your first snippet with product function):
from loggerforhousing import logger
Does it help?

Prevent custom assert from showing in traceback of python unittest

I'd like to add some custom assert methods to a TestCase. As a simple example, I've just put one inside the test class below. It works as expected, but when the output is generated the traceback includes the custom assert in the output.
What is the step necessary to make it behave like assertEqual()? The code for assertEqual is in TestCase, but the actual line that raises the assertion does not appear in the traceback. What do I need to do to make test_something2's output look more like test_something1's?
import unittest
class TestCustomAssert(unittest.TestCase):
def assertSomething(self, s):
self.assertEqual(s, 'something')
def test_something1(self):
self.assertEqual('foo', 'something')
def test_something2(self):
self.assertSomething('foo')
if __name__ == '__main__':
unittest.main()
Output
python3 custom_assert.py
FF
======================================================================
FAIL: test_something1 (__main__.TestCustomAssert)
----------------------------------------------------------------------
Traceback (most recent call last):
File "custom_assert.py", line 8, in test_something1
self.assertEqual('foo', 'something')
AssertionError: 'foo' != 'something'
- foo
+ something
======================================================================
FAIL: test_something2 (__main__.TestCustomAssert)
----------------------------------------------------------------------
Traceback (most recent call last):
File "custom_assert.py", line 10, in test_something2
self.assertSomething('foo')
File "custom_assert.py", line 6, in assertSomething
self.assertEqual(s, 'something')
AssertionError: 'foo' != 'something'
- foo
+ something
----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (failures=2)
unittest doesn't print tracebacks from frames that have __unittest=True in their globals.
From unittest.result:
def _is_relevant_tb_level(self, tb):
return '__unittest' in tb.tb_frame.f_globals
So, if you make a helper module, you can emulate that behavior:
helper.py:
__unittest = True
def assert_stuff(s):
assert s == 'something', "%s is not something" % s
Now you can call this helper from your test case.
I guess that one could make a very neat decorator that make such magic more automatic without a helper module but IMHO you shouldn't make effort to reduce the traceback anyway.

Python version related error

I am trying to generate an HTML test report by using Selenium webdriver library HTMLTestRunner. I am using Python 3.4 version and I have a version related error. Refer following snippet.
import unittest`enter code here`
import HTMLTestRunner
from selenium import webdriver
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.common.keys import Keys
class GreenlamTest(unittest.TestCase):
#classmethod
def setUp(cls):
cls.driver=webdriver.Firefox()
cls.driver.implicitly_wait(30)
cls.driver.maximize_window()
cls.driver.get('https://www.google.co.in')
def test_checkTitle(self):
assert "Google" in self.driver.title
def test_searchtest(self):
driver = self.driver
elem = self.driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
#classmethod
def tearDown(cls):
cls.driver.quit()
if __name__ == '__main__':
HTMLTestRunner.main
Output
Finding files... done.
Traceback (most recent call last):
File "C:\Users\vaibhav\Desktop\Selenium Softwares\eclipse-jee-luna-SR2-win32-x86_64\eclipse\plugins\org.python.pydev_4.0.0.201504132356\pysrc\pydev_runfiles.py", line 468, in __get_module_from_str
mod = __import__(modname)
File "C:\Users\vaibhav\Desktop\Selenium Softwares\Practice\pythondemo\Htmlreport.py", line 2, in <module>
import HTMLTestRunner
File "C:\Users\vaibhav\Desktop\Selenium Softwares\Practice\pythondemo\HTMLTestRunner.py", line 94, in <module>
import StringIO
ImportError: No module named 'StringIO'
ERROR: Module: Htmlreport could not be imported (file: C:\Users\vaibhav\Desktop\Selenium Softwares\Practice\pythondemo\Htmlreport.py).
Importing test modules ... done.
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
You are getting error because your folder name Selenium Softwares has a space in it where your Htmlreport is present. Replace the folder name to exclude space out of it, probably an underscore or camelCase, etc... like this Selenium_Softwares . Here's how -
file: C:\Users\vaibhav\Desktop\Selenium_Softwares\Practice\pythondemo\Htmlreport.py)
Hope this helps.

Error to compile file PyObject (Gtk ) with Pydev

I'm build application with pyobject (gtk) in Pydev , but i'm try to create a window
the following way:
Class Ventana
from gi.overrides import Gtk
class Ventana( Gtk.Window ):
def __init__( self,titulo ):
Gtk.Window.__init__(self,title=titulo )
self.connect("delete-event",Gtk.main_quit )
Class Aplicacion( Main):
def main():
win = Ventana()
if __name__ == '__main__':
main()
but I'm try to compile te App, show the following mistake:
Traceback (most recent call last):
File "/home/demian/workspace/NidhugsRPG/nidhugs/presentacion/Consola.py", line 6, in
<module>
from gi.overrides import Gtk
File "/usr/lib/python3/dist-packages/gi/overrides/Gtk.py", line 35, in <module>
Gtk = modules['Gtk']._introspection_module
KeyError: 'Gtk'
I'm try use the import
from gi.repository import Gtk
but, not works,because moudule not found.So i'm use the import:
from gi.overrides import Gtk
¿How to fix my trouble?
Sorry for my bad English
Thanks.

Resources