Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Writing unittests #9

Closed
fractaledmind opened this issue Mar 20, 2014 · 1 comment
Closed

Writing unittests #9

fractaledmind opened this issue Mar 20, 2014 · 1 comment

Comments

@fractaledmind
Copy link
Contributor

So I'm starting to create unit tests for ZotQuery, and I'm struggling to get alfred-workflow to work with me. While I'm certain to have other issues, my initial problem concerns the assertEqual function within unittest.

Specifically, I can't assertEqual when running a test query through my filter script. Here's my function:

def test_filter(self):
        args = [u'tester', u'general']
        oargs = sys.argv[:]
        sys.argv = [oargs[0]] + [s.encode('utf-8') for s in args]
        xml_res = filter.main(self.wf)
        no_res = """<?xml version="1.0" encoding="utf-8"?>
<items><item valid="no"><title>Error!</title><subtitle>No results found.</subtitle><icon>icons/n_error.png</icon></item></items>"""
        try:
            self.assertEqual(xml_res, no_res)
        finally:
            sys.argv = oargs[:]

When I run filter.main(self.wf), it will print the "No Results" xml to the console, but I can't trap it in a var to assertEqual. How can I write unittests for a workflow written in alfred-workflow?

@deanishe
Copy link
Owner

Typically, you shouldn't call your main function in unit tests. You should keep it simple and move the functionality to other functions/classes that you call from a barebones main. The general rule is that if you can't isolate a function to unit test it, it isn't designed well and you need to refactor the code anyway.

That won't help you capture the output of Workflow however. To do that you would temporarily reassign sys.stdout (which is what Workflow writes its XML output to) to a StringIO object and read the results from there:

from StringIO import StringIO

fp = StringIO()

# reassign sys.stdout to StringIO instance
orig_stdout = sys.stdout
sys.stdout = fp

# whatever code that makes `Workflow` do its thing here
wf.send_feedback()

# set sys.stdout back to its proper value (a `finally` clause may be a better place for this)
sys.stdout = orig_stdout

# retrieve Workflow output from the StringIO instance
self.assertEqual(fp.getvalue(), expected_value)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants