Skip to content

Instantly share code, notes, and snippets.

@diminoten
Last active December 30, 2015 13:29
Show Gist options
  • Save diminoten/7835820 to your computer and use it in GitHub Desktop.
Save diminoten/7835820 to your computer and use it in GitHub Desktop.
An example of the problem I'm having unit testing a custom nose plugin.
"""
Will need to install mock and nose for this example to work.
"""
import unittest
from mock import Mock
from nose.plugins import Plugin
from nose.plugins import PluginTester
class ExamplePlugin(Plugin):
name = 'example-plugin'
def options(self, parser, env):
super(ExamplePlugin, self).options(parser, env)
parser.add_option(
"--example-arg",
"-u",
action="store",
type="string",
dest="example_arg"
)
def configure(self, options, conf):
super(ExamplePlugin, self).configure(options, conf)
if not self.enabled:
return
if options.example_arg is None:
log.error('No example arg, disabling example plugin.')
self.enabled = False
return
self.example = options.example_arg
self.testCount = 0
def handleResult(self, result, test, err=None):
#In my actual app, there are some HTTP calls made at this point.
pass
def addError(self, test, err):
self.handleResult('ERROR', test, err)
def addFailure(self, test, err):
self.handleResult('FAILURE', test, err)
def addSuccess(self, test):
self.handleResult('SUCCESS', test)
def beforeTest(self, test):
#Some additional HTTP calls are made here.
self.testCount += 1
class TestExamplePlugin(PluginTester, unittest.TestCase):
activate = '--with-example-plugin'
args = ['--example-arg=foo']
test_plugin = ExamplePlugin()
test_plugin.handleResult = Mock()
plugins = [test_plugin]
def test_example_arg(self):
assert self.test_plugin.example == 'foo'
def test_initial_test_count(self):
assert self.test_plugin.testCount == 0
def test_handle_calls(self):
assert self.test_plugin.handleResult.called == True, \
"Why does this fail to work?"
def test_handle_calls_after_setUp(self):
self.setUp()
assert self.test_plugin.handleResult.called == True, \
"This fails too; why?"
def test_before_test_call(self):
assert self.test_plugin.testCount == 2, \
"This should be 2, as there are two tests to run in the sample test suite, but it's not."
def makeSuite(self):
class TC(unittest.TestCase):
def runTest(self):
assert True
def runAnotherTest(self):
assert False
return unittest.TestSuite([TC()])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment