base.testing

A Unit Test Framework

There are likely a hundred libraries to run unit tests. This is ours.

base.TestCase

At the highest level, you define a test cases like this:

class MyTest(base.TestCase):
  def Run(self):
    # ... do stuff ...
    self.LogResult(passed, message)

This adds a test case to the registry. Then from some module that you call as your entrypoint, you do this:

base.TestRunner().RunFromCommandLine()

This will run every registered test case.

self.LogResult()

A test case may call LogResult() more than once.

The test is considered passed only if all the results have passed. If the test finishes without logging any result, it will pass so long as the return value is not exactly False. That is, returning None will pass, but returning False will fail.

self.Try()

self.Try(...) lets you pass a python expression as a string. That expression is evaluated, the result converted to a bool, and passed to self.LogResult(). Exceptions are caught.

self.Try('1 == 1')    # Succeeds
self.Try('1 == 2')    # Fails
self.Try('1 =  2')    # also Fails

base.TestContext

Each test case can exist within a Context, which manages setup and cleanup behavior.

class MyTestContext(base.TestContext):

  def SetUp(self):
    # ... do stuff ...

  def CleanUp(self):
    # ... do stuff ...

Then your test case attaches to the context like this:

class MyTest(base.TestCase):
  TEST_CONTEXT = MyTestContext

Alternately, you can define a context for an entire module:

class MyTestContext(base.TestModuleContext):
    # ... SetUp() and CleanUp() ...

Every test case within the same python module as this context will automatically run within this context.

A test case may have both a module context and a test case context at the same time.

Commands and Command Line

A TestCase usually will have a Run() method. However, other entry methods can also be created, and called from the command line. Specifically, any no-argument method on the class can be registered as an entrypoint:

class MyTest(base.TestCase):

  COMMANDS = ['Run', 'Elsewyze']

  def Elsewyze(self):
    pass

From the command line, you would call this alternate entrypoint like this:

./my_test_program.py --only mymodule.MyTest Elsewyze

Our command line processing also knows the alternate entrypoint list:

./my_test_program.py list

Again, inside, my_test_program would be loading whatever code it needs to test, registering test cases, then calling base.TestRunner().RunFromCommandLine()

For example, our own octobase unit tests (what scant few there are) also use this framework. Our own test runner program, in its entirety, looks like so:

#!/usr/bin/env python3

import base

if __name__ == '__main__':
  base.TestRunner(basetest=True).RunFromCommandLine()

The only difference between this and your own is we pass the flag basetest=True to enable all our own tests. (In your code, you probably don’t need to be running our test cases.)