Search Results

Search found 156 results on 7 pages for 'unittest'.

Page 1/7 | 1 2 3 4 5 6 7  | Next Page >

  • How to pass variables using Unittest suite

    - by chrissygormley
    Hello I have test's using unittest. I have a test suite and I am trying to pass variables through into each of the tests. The below code shows the test suite used. class suite(): def suite(self): #Function stores all the modules to be tested modules_to_test = ('testmodule1', 'testmodule2') alltests = unittest.TestSuite() for module in map(__import__, modules_to_test): alltests.addTest(unittest.findTestCases(module)) return alltests It calls tests, I would like to know how to pass variables into the tests from this class. An example test script is below: class TestThis(unittest.TestCase): def runTest(self): assertEqual('1', '1') class TestThisTestSuite(unittest.TestSuite): # Tests to be tested by test suite def makeTestThisTestSuite(): suite = unittest.TestSuite() suite.addTest("TestThis") return suite def suite(): return unittest.makeSuite(TestThis) if __name__ == '__main__': unittest.main() So from the class suite() I would like to enter in a value to change the value that is in assert value. Eg. assertEqual(self.value, '1'). I have tried sys.argv for unittest and it doesn't seem to work. Thanks for any help.

    Read the article

  • Problem with sys.argv[1] when unittest module is in a script

    - by chrissygormley
    Hello, I have a script that does various things and access paramenters using sys.argv but when the script gets to the unittest part of the code it says there is no module for this. The script that I have is: class MyScript(): def __init__(self): self.value = sys.argv[1] def hello(self): print self.value def suite(self): modules_to_test = ('external_sanity_onvif', 'starttest') alltests = unittest.TestSuite() for module in map(__import__, modules_to_test): alltests.addTest(unittest.findTestCases(module)) return alltests if __name__ == '__main__': Run = MyScript() Run.hello() log_file = 'log_file.txt' test_file = open(log_file, "w") runner = unittest.TextTestRunner(test_file) unittest.main(defaultTest='Run.suite', testRunner=runner) Say I enter ./script.py Hello in the command line. The error I get is: AttributeError: 'module' object has no attribute 'Hello' If I remove the unittest module it works. Also if I remove the testrunner log and leave it at: unittest.main(defaultTest='Run.suite') This still doesn't work. Can anyone help. Thanks

    Read the article

  • Problem's running unittest test suite OO

    - by chrissygormley
    Hello, I have a test suite to perform smoke tests. I have all my script stored in various classes but when I try and run the test suite I can't seem to get it working if it is in a class. The code is below: (a class to call the tests) from alltests import SmokeTests class CallTests(SmokeTests): def integration(self): self.suite() if __name__ == '__main__': run = CallTests() run.integration() And the test suite: class SmokeTests(): def suite(self): #Function stores all the modules to be tested modules_to_test = ('external_sanity', 'internal_sanity') alltests = unittest.TestSuite() for module in map(__import__, modules_to_test): alltests.addTest(unittest.findTestCases(module)) return alltests unittest.main(defaultTest='suite') This output's an error: Attribute Error: 'module' object has no attribute 'suite' So I can see how to call a normal function defined but I'm finding it difficult calling in the suite. In one of the tests the suite is set up like so: class InternalSanityTestSuite(unittest.TestSuite): # Tests to be tested by test suite def makeInternalSanityTestSuite(): suite = unittest.TestSuite() suite.addTest(TestInternalSanity("BasicInternalSanity")) suite.addTest(TestInternalSanity("VerifyInternalSanityTestFail")) return suite def suite(): return unittest.makeSuite(TestInternalSanity) Can anyone help me with getting this running? Thanks for any help in advance.

    Read the article

  • Proper structure for many test cases in Python with unittest

    - by mellort
    I am looking into the unittest package, and I'm not sure of the proper way to structure my test cases when writing a lot of them for the same method. Say I have a fact function which calculates the factorial of a number; would this testing file be OK? import unittest class functions_tester(unittest.TestCase): def test_fact_1(self): self.assertEqual(1, fact(1)) def test_fact_2(self): self.assertEqual(2, fact(2)) def test_fact_3(self): self.assertEqual(6, fact(3)) def test_fact_4(self): self.assertEqual(24, fact(4)) def test_fact_5(self): self.assertFalse(1==fact(5)) def test_fact_6(self): self.assertRaises(RuntimeError, fact, -1) #fact(-1) if __name__ == "__main__": unittest.main() It seems sloppy to have so many test methods for one method. I'd like to just have one testing method and put a ton of basic test cases (ie 4! ==24, 3!==6, 5!==120, and so on), but unittest doesn't let you do that. What is the best way to structure a testing file in this scenario? Thanks in advance for the help.

    Read the article

  • Run unittest in a Class

    - by chrissygormley
    Hello, I have a test suite to perform smoke tests. I have all my script stored in various classes but when I try and run the test suite I can't seem to get it working if it is in a class. The code is below: (a class to call the tests) from alltests import SmokeTests class CallTests(SmokeTests): def integration(self): self.suite() if __name__ == '__main__': run = CallTests() run.integration() And the test suite: class SmokeTests(): def suite(self): #Function stores all the modules to be tested modules_to_test = ('external_sanity', 'internal_sanity') alltests = unittest.TestSuite() for module in map(__import__, modules_to_test): alltests.addTest(unittest.findTestCases(module)) return alltests if __name__ == '__main__': unittest.main(defaultTest='suite') So I can see how to call a normal function defined but I'm finding it difficult calling in the suite. In one of the tests the suite is set up like so: class InternalSanityTestSuite(unittest.TestSuite): # Tests to be tested by test suite def makeInternalSanityTestSuite(): suite = unittest.TestSuite() suite.addTest(TestInternalSanity("BasicInternalSanity")) suite.addTest(TestInternalSanity("VerifyInternalSanityTestFail")) return suite def suite(): return unittest.makeSuite(TestInternalSanity) If I have def suite() inside the class SmokeTests the script executes but the tests don't run but if I remove the class the tests run. I run this as a script and call in variables into the tests. I do not want to have to run the tests by os.system('python tests.py'). I was hoping to call the tests through the class I have like any other function. This need's to be called from a class as the script that I'm calling it from is Object Oriented. If anyone can get the code to be run using Call Tests I would appreciate it alot. Thanks for any help in advance.

    Read the article

  • use/run python's 2to3 as or like a unittest

    - by Vincent
    I have used the 2to3 utility to convert code from the command line. What I would like to do is run it basically as a unittest. Even if it tests the file rather than parts(funtions, methods...) as would be normal for a unittest. It does not need to be a unittest and I don't what to automatically convert the files I just want to monitor the py3 compliance of files in a unittest like manor. I can't seem to find any documentation or examples for this. An example and/or documentation would be great. Thanks

    Read the article

  • Python unittest: Generate multiple tests programmatically?

    - by Rosarch
    I have a function to test, under_test, and a set of expected input/output pairs: [ (2, 332), (234, 99213), (9, 3), # ... ] I would like each one of these input/output pairs to be tested in its own test_* method. Is that possible? This is sort of what I want, but forcing every single input/output pair into a single test: class TestPreReqs(unittest.TestCase): def setUp(self): self.expected_pairs = [(23, 55), (4, 32)] def test_expected(self): for exp in self.expected_pairs: self.assertEqual(under_test(exp[0]), exp[1]) if __name__ == '__main__': unittest.main()

    Read the article

  • UnitTest++ constructing fixtures multiple times?

    - by Peter
    I'm writing some unit tests in UnitTest++ and want to write a bunch of tests which share some common resources. I thought that this should work via their TEST_FIXTURE setup, but it seems to be constructing a new fixture for every test. Sample code: #include <UnitTest++.h> struct SomeFixture { SomeFixture() { // this line is hit twice } }; TEST_FIXTURE(SomeFixture, FirstTest) { } TEST_FIXTURE(SomeFixture, SecondTest) { } I feel like I must be doing something wrong; I had thought that the whole point of having the fixture was so that the setup/teardown code only happens once. Am I wrong on this? Is there something else I have to do to make it work that way?

    Read the article

  • unittest tests reuse for family of classes

    - by zaharpopov
    I have problem organizing my unittest based class test for family of tests. For example assume I implement a "dictionary" interface, and have 5 different implementations want to testing. I do write one test class that tests a dictionary interface. But how can I nicely reuse it to test my all classes? So far I do ugly: DictType = hashtable.HashDict In top of file and then use DictType in test class. To test another class I manually change the DictType to something else. How can do this otherwise? Can't pass arguments to unittest classes so is there a nicer way?

    Read the article

  • How to run unittest under pydev for Django?

    - by photon
    I configured properties for my django project under pydev. I can run the django app under pydev or under console window. I can also run unittest for app under console window. But I have problems to run unittest under pydev. I guess it's something related to run configurations of pydev, so I made several trials, but with no success. Once I got messages like this: ImportError: Could not import settings 'D:\django_projects\MyProject' (Is it on sys.path? Does it have syntax errors?): No module named D:\django_projects\MyProject ERROR: Module: MyUnittestFile could not be imported. Another time I got messages like this: ImportError: Could not import settings 'MyProject.settngs' (Is it on sys.path? Does it have syntax errors?): No module named settngs 'ERROR: Module: MyUnittestFile could not be imported. I use pydev 1.5.6 on eclipse and windows xp. Any ideas for this problem?

    Read the article

  • How to run unittest for Django?

    - by photon
    I configured properties for my django project under pydev. I can run the django app under pydev or under console window. But I have problems to run unittest under pydev. I cannot run unittest for app under console window either. I guessed it's something related to run configurations of pydev, so I made several trials, but with no success. Once I got messages like this: ImportError: Could not import settings 'D:\django_projects\MyProject' (Is it on sys.path? Does it have syntax errors?): No module named D:\django_projects\MyProject ERROR: Module: MyUnittestFile could not be imported. Another time I got messages like this: ImportError: Could not import settings 'MyProject.settngs' (Is it on sys.path? Does it have syntax errors?): No module named settngs 'ERROR: Module: MyUnittestFile could not be imported. I use pydev 1.5.6 on eclipse and windows xp. Any ideas for this problem? Now I think it's not something related to pydev, thanks for Xavier Ho's suggestion.

    Read the article

  • UnitTest++ creates cmd windows, which can't be closed

    - by Simon
    Hello, I have a setup for using UnitTest++ like this in VS2008. Sometimes the cmd window, which shows the console output of the unit tests just hangs. I can move the window, resize and stuff, but I'm unable to close it. I see the window in the App tab of the Task Manager, but not in the Process tab, "Switch to process" doesn't work either. Stop debugging or closing VS is also no help, it seems VS has lost control over this window. If this cmd window is lost, I'm unable to shutdown my computer, which is pretty annoying Any hints?

    Read the article

  • Testing with Unittest Python

    - by chrissygormley
    Hello, I am runninig test's with Python Unittest. I am running tests but I want to do negative testing and I would like to test if a function throw's an exception, it passes but if no exception is thrown the test fail's. The script I have is: try: result = self.client.service.GetStreamUri(self.stream, self.token) self.assertFalse except suds.WebFault, e: self.assertTrue else: self.assertTrue This alway's passes as True even when the function work's perfectly. I have also tried various other way's including: try: result = self.client.service.GetStreamUri(self.stream, self.token) self.assertFalse except suds.WebFault, e: self.assertTrue except Exception, e: self.assertTrue Does anyone have any suggestions? Thanks

    Read the article

  • PyQt and unittest - how to handle signals and slots

    - by Einar
    Hello, some small application I'm developing uses a module I have written to check certain web services via a REST API. I've been trying to add unit tests to it so I don't break stuff, and I stumbled upon a problem. I use a lot of signal-slot connections to perform operations asynchronously. For example a typical test would be (pseudo-Python), with postDataDownloaded as a signal: def testConnection(self): "Test connection and posts retrieved" def length_test(): self.assertEqual(len(self.client.post_data), 5) self.client.postDataReady.connect(length_test) self.client.get_post_list(limit=5) Now, unittest will report this test to be "ok" when running, regardless of the result (as another slot is being called), even if asserts fail (I will get an unhandled AssertionError). Example when deliberatiely making the test fail: Test connection and posts retrieved ... ok [... more tests...] OK Traceback (most recent call last): [...] AssertionError: 4 != 5 The slot inside the test is merely an experiment: I get the same results if it's outside (instance method). I also have to add that the various methods I'm calling all make HTTP requests, which means they take a bit of time (I need to mock the request - in the mean time I'm using SimpleHTTPServer to fake the connections and give them proper data). Is there a way around this problem?

    Read the article

  • How to Return Variable for all tests to use Unittest

    - by chrissygormley
    Hello, I have a Python script and I am trying to set a variable so that if the first test fail's the rest of then will be set to fail. The script I have so far is: class Tests(): def function: result function.......... def errorHandle(self): return self.error def sudsPass(self): try: result = self.client.service.GetStreamUri(self.stream, self.token) except suds.WebFault, e: assert False except Exception, e: pass finally: if 'result' in locals(): self.error = True self.errorHandle() assert True else: self.error = False self.errorHandle() assert False def sudsFail(self): try: result = self.client.service.GetStreamUri(self.stream, self.token) except suds.WebFault, e: assert False except Exception, e: pass finally: if 'result' in locals() or self.error == False: assert False else: assert True class GetStreamUri(TestGetStreamUri): def runTest(self): self.sudsPass() class GetStreamUriProtocolFail(TestGetStreamUri): def runTest(self): self.stream.Transport.Protocol = "NoValue" self.errorHandle() self.sudsFail() if __name__ == '__main__': unittest.main() I am trying to get self.error to be set to False if the first test fail. I understand that it is being set in another test but I was hoping someone could help me find a solution to this problem using some other means. Thanks PS. Please ignore the strange tests. There is a problem with the error handling at the moment.

    Read the article

  • Unittest test case only touches the file name

    - by Chen OT
    I was told that unittest is fast and the tests which touches DB, across network, and touches FileSystem are not unittest. In one of my testcases, its input are the file names (amount about 300~400) under a specific folder. Although these input are part of file system, the execution time of this test is very fast. Should I moved this test, which is fast but touches file system, to higher level test?

    Read the article

  • python unittest howto

    - by zubin71
    I`d like to know how I could unit-test the following module. def download_distribution(url, tempdir): """ Method which downloads the distribution from PyPI """ print "Attempting to download from %s" % (url,) try: url_handler = urllib2.urlopen(url) distribution_contents = url_handler.read() url_handler.close() filename = get_file_name(url) file_handler = open(os.path.join(tempdir, filename), "w") file_handler.write(distribution_contents) file_handler.close() return True except ValueError, IOError: return False

    Read the article

  • Running unittest with typical test directory structure.

    - by Major Major
    The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own test directory: new_project/ antigravity/ antigravity.py test/ test_antigravity.py setup.py etc. for example see this Python project howto. My question is simply What's the usual way of actually running the tests? I suspect this is obvious to everyone except me, but you can't just run python test_antigravity.py from the test directory as its import antigravity will fail as the module is not on the path. I know I could modify PYTHONPATH and other search path related tricks, but I can't believe that's the simplest way - it's fine if you're the developer but not realistic to expect your users to use if they just want to check the tests are passing. The other alternative is just to copy the test file into the other directory, but it seems a bit dumb and misses the point of having them in a separate directory to start with. So, if you had just downloaded the source to my new project how would you run the unit tests? I'd prefer an answer that would let me say to my users: "To run the unit tests do X."

    Read the article

  • Configuring a library to be included with C++ test

    - by vrish88
    Hello, I would like to utilize the UnitTest++ library in a testing file. However, I am having some difficulty getting the library to be included at compile time. So here is my current directory structure: tests/ UnitTests++/ libUnitTest++.a src/ UnitTests++.h unit/ test.cpp I have just used the UnitTest++ getting started guide to just get the library setup. Here is test.cpp: // test.cpp #include <UnitTest++.h> TEST(FailSpectacularly) { CHECK(false); } int main() { return UnitTest::RunAllTests(); } And I am currently trying to compile with: gcc -lUnitTest++ -L../UnitTest++/ -I../UnitTest++/src/ test.cpp I am currently getting a bunch output with ld: symbol(s) not found at the end. So how would I be able to get the UnitTest++ library properly included when this program is compiled? I am on a Mac and I'd also like for there to be an easy way for people on a Linux machine to run these same tests. Whew, I hope this provides enough information, if not please let me know.

    Read the article

  • Caching result of setUp() using Python unittest

    - by dbr
    I currently have a unittest.TestCase that looks like.. class test_appletrailer(unittest.TestCase): def setup(self): self.all_trailers = Trailers(res = "720", verbose = True) def test_has_trailers(self): self.failUnless(len(self.all_trailers) > 1) # ..more tests.. This works fine, but the Trailers() call takes about 2 seconds to run.. Given that setUp() is called before each test is run, the tests now take almost 10 seconds to run (with only 3 test functions) What is the correct way of caching the self.all_trailers variable between tests? Removing the setUp function, and doing.. class test_appletrailer(unittest.TestCase): all_trailers = Trailers(res = "720", verbose = True) ..works, but then it claims "Ran 3 tests in 0.000s" which is incorrect.. The only other way I could think of is to have a cache_trailers global variable (which works correctly, but is rather horrible): cache_trailers = None class test_appletrailer(unittest.TestCase): def setUp(self): global cache_trailers if cache_trailers is None: cache_trailers = self.all_trailers = all_trailers = Trailers(res = "720", verbose = True) else: self.all_trailers = cache_trailers

    Read the article

  • Unittest and mock

    - by user1410756
    I'm testing with unittest in python and it's ok. Now, I have introduced mock and I need to resolve a question. This is my code: from mock import Mock import unittest class Matematica(object): def __init__(self, op1, op2): self.op1 = op1 self.op2 = op2 def adder(self): return self.op1 + self.op2 def subs(self): return abs(self.op1 - self.op2) def molt(self): return self.op1 * self.op2 def divid(self): return self.op1 / self.op2 class TestMatematica(unittest.TestCase): """Test della classe Matematica""" def testing(self): """Somma""" mat = Matematica(10,20) self.assertEqual(mat.adder(),30) """Sottrazione""" self.assertEqual(mat.subs(),10) class test_mock(object): def __init__(self, matematica): self.matematica = matematica def execute(self): self.matematica.adder() self.matematica.adder() self.matematica.subs() if __name__ == "__main__": result = unittest.TextTestRunner(verbosity=2).run(TestMatematica('testing')) a = Matematica(10,20) b = test_mock(a) b.execute() mock_foo = Mock(b.execute)#return_value = 'rafa') mock_foo() print mock_foo.called print mock_foo.call_count print mock_foo.method_calls This code is functionally and result of print is: True, 1, [] . Now, I need to count how many times are called self.matematica.adder() and self.matematica.subs() . THANKS

    Read the article

  • Why `#import("dart:unittest")` can't run?

    - by Freewind
    I write some dart test code: #import("dart:unittest"); main() { test('this is a test', () { int x = 2+3; expect(x).equals(5); }); } It doesn't display any error in dart editor, but when I press the "run" button, it reports: Do not know how to load 'dart:unittest''file:///home/freewind/dev/dart/editor /samples/shuzu.org/test/model_test.dart': Error: line 1 pos 1: library handler failed #import("dart:unittest"); ^ I see there is a "dart:unittest" library in my dart-sdk. Why it can't be run?

    Read the article

  • Python unittest with expensive setup

    - by Staale
    My test file is basically: class Test(unittest.TestCase): def testOk(): pass if __name__ == "__main__": expensiveSetup() try: unittest.main() finally: cleanUp() However, I do wish to run my test through Netbeans testing tools, and to do that I need unittests that don't rely on an environment setup done in main. Looking at http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest - it recommends using Nose. However, I don't think Netbeans supports this. I didn't find any information indicating that it does. Additionally, I am the only one here actually writing tests, so I don't want to introduce additional dependencies for the other 2 developers unless they are needed. How can I do the setup and cleanup once for all the tests in my TestSuite? The expensive setup here is creating some files with dummy data, as well as setting up and tearing down a simple xml-rpc server. I also have 2 test classes, one testing locally and one testing all methods over xml-rpc.

    Read the article

  • Python, unit test - Pass command line arguments to setUp of unittest.TestCase

    - by sberry2A
    I have a script that acts as a wrapper for some unit tests written using the Python unittest module. In addition to cleaning up some files, creating an output stream and generating some code, it loads test cases into a suite using unittest.TestLoader().loadTestsFromTestCase() I am already using optparse to pull out several command-line arguments used for determining the output location, whether to regenerate code and whether to do some clean up. I also want to pass a configuration variable, namely an endpoint URI, for use within the test cases. I realize I can add an OptionParser to the setUp method of the TestCase, but I want to instead pass the option to setUp. Is this possible using loadTestsFromTestCase()? I can iterate over the returned TestSuite's TestCases, but can I manually call setUp on the TestCases? ** EDIT ** I wanted to point out that I am able to pass the arguments to setUp if I iterate over the tests and call setUp manually like: (options, args) = op.parse_args() suite = unittest.TestLoader().loadTestsFromTestCase(MyTests.TestSOAPFunctions) for test in suite: test.setUp(options.soap_uri) However, I am using xmlrunner for this and its run method takes a TestSuite as an argument. I assume it will run the setUp method itself, so I would need the parameters available within the XMLTestRunner. I hope this makes sense.

    Read the article

  • How can I do such a typical unittest?

    - by Malcom.Z
    This is a simple structure in my project: MyAPP--- note--- __init__.py views.py urls.py test.py models.py auth-- ... template--- auth--- login.html register.html note--- noteshow.html media--- css--- ... js--- ... settings.py urls.py __init__.py manage.py I want to make a unittest which can test the noteshow page working propeyly or not. The code: from django.test import TestCase class Note(TestCase): def test_noteshow(self): response = self.client.get('/note/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, '/note/noteshow.html') The problem is that my project include an auth mod, it will force the unlogin user redirecting into the login.html page when they visit the noteshow.html. So, when I run my unittest, in the bash it raise an failure that the response.status_code is always 302 instead of 200. All right though through this result I can check the auth mod is running well, it is not like what I want it to be. OK, the question is that how can I make another unittest to check my noteshow.template is used or not? Thanks for all. django version: 1.1.1 python version: 2.6.4 Use Eclipse for MAC OS

    Read the article

1 2 3 4 5 6 7  | Next Page >