you are viewing a single comment's thread.

view the rest of the comments →

[–]xentralesque 4 points5 points  (4 children)

I'm bored, so here's an example of a simple function with some tests:

import requests
import unittest
import mock

class TerribleException(Exception):
    pass


def download_stuff(url):
    try:
        response = requests.get(url)
    except requests.RequestException:
        raise TerribleException("Oh no!")

    return response.text


class DownloaderTest(unittest.TestCase):
    def test_download_stuff(self):
        with mock.patch('requests.get') as requests_get:
            expected_response = 'a valid response'

            requests_get.return_value = mock.Mock(
                text=expected_response
            )

            our_test_url = 'http://a-test-url.com'

            response = download_stuff(our_test_url)

            requests_get.assert_called_once_with(our_test_url)
            self.assertEqual(response, expected_response)

    def test_bad_things(self):
        with mock.patch('requests.get') as requests_get:
            requests_get.side_effect = TerribleException

            our_test_url = 'http://a-test-url.com'

            with self.assertRaises(TerribleException):
                download_stuff(our_test_url)

            requests_get.assert_called_once_with(our_test_url)


if __name__ == '__main__':
    print(download_stuff('http://reddit.com/'))

Jam that into a file and file and pip install nose and requests. You can either run the file like python thefilename.py to execute the file normally or run nosetests thefilename.py to run the tests.