0

I developed a crawler and it's unit-tests (mainly to validate XPATHs). I want to run specific unit-tests before script execution in order to be sure that HTML structure has not changed and existing XPATHs still working. I don't want the output of unit-test, just a flag: passed or failed.

for example:

tests.py:

import unittest

class CrwTst(unittest.TestCase):
    def test_1(self):
        [..]

crawler.py

class Crawler(object):
    def action_1(self):
        [..]

and I want to work like:

if CrwTst.test_1() is True:
    Crawler.action_1()
4
  • Tests raise Exceptions (usually AssertionError) when they fail. So as long as you don't catch that error you can probably do test_my_thing(); action1(). Also ZdaR is right, this seems an odd use of unit tests (which are intended to test your code itself, not to validate data you pass to your code).
    – Tom Dalton
    May 17, 2018 at 9:40
  • 2
    Why create a test case for this, You can create a validation function which either returns True or False
    – ZdaR
    May 17, 2018 at 9:40
  • @ZdaR I have many test cases and I think it's better to keep this kind of validations with other unit-tests. I'm newbie to unit-testing development and maybe you are right. May 17, 2018 at 9:46
  • @TomDalton I'm trying to import CrwTst to crawler.py from tests import CrwTst and I'm getting import error ImportError: cannot import name CrwTst May 17, 2018 at 9:48

1 Answer 1

1

You could potentially do this:

crawler.py

import unittest
from tests import CrwTst

if unittest.TextTestRunner().run(CrwTst('test_1')).wasSuccessful():
    Crawler.action_1()

Note however that you may run into an issue with circular imports, because your test presumably already depends on Crawler, and what you are looking to do will make the Crawler depend on the test. This will likely manifest itself as ImportError: cannot import name CrwTst.

To resolve that, you can dynamically import the CrwTst.

crawler.py

import unittest

def function_that_runs_crawler():
    from tests import CrwTst  # Dynamically import to resolve circular ref

    if unittest.TextTestRunner().run(CrwTst('test_1')).wasSuccessful():
        Crawler.action_1()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.