Skip to content

Latest commit

 

History

History
170 lines (115 loc) · 4.16 KB

README.md

File metadata and controls

170 lines (115 loc) · 4.16 KB

Unit Testing with Python 3

Summary

Examples

Mocking

Tutorials

Mocking

Coverage

Just do this...

# coverage run --source=. -m unittest discover
# coverage report -m
python -m coverage run --source=. -m unittest discover
# generate an inline report
python -m coverage report -m
# generates an html page
python -m coverage html -d coverage_html

# your html result will be located in coverage_html/index.html

DAFUCK IS A TEST?

If you don't fucking know what is a test, let me tell ya.

A test is a specification for program.

cool..

What about Unit Testing

The same as for the test, dãã. But for a program unity. For a method, if you wish.

My method

def who(ze_bula):
    return "My {}".format(ze_bula)

Can be tested with

import unittest

class TestWho(unittest.TestCase):
    def test_who(self):
        expected = "My BotoFe"
        actual = who("BotoFe")
        self.assertEqual(expected, actual)

Does the code makes fucking sense? No fucking way!!

But I guarantee to you that is tested.

Mocks?

Yeah!!

It's awesome aswell.

You don't need to call private functions that does horrifyingly horrifying things that you don't care. You can mock them.

Let's say I have a method called mama(). mama() does a lot of things. mama() calls a weird function called weirdo()

# weirdo() is a method you will want to mock
def weirdo(a_string):
    # Do a bunch of bunch of bunches of things
    # Do more things
    # Opens a fucking file
    # OMG. weirdo() is making 500 HTTP requests
    # weirdo is being weirdo
    return a_string

# mama() is a method you will want to test
def mama():
    i_am_a_variable = "IMA STRING"
    weirdo_response = weirdo(i_am_a_variable)
    return weirdo_response + '1'

And let's say, for the sake of this tutorial that probably only I will read, that you are testing mama() and you want to fake a return of weirdo().

Is it possible?

Yeah, it is. Look at this:

import unittest
from unittest.mock import patch

class TestMama(unittest.TestCase):

    @patch('{}.weirdo'.format(__name__))
    def test_mama(self, mock_weirdo):
        mock_weirdo.return_value = "IMA weirdo"

        expected = "IMA weirdo1"
        actual = mama()

        self.assertEqual(expected, actual)

OMG.. What did happened here?

Did you see this patch()? WTF? Could you understand what he is doing? Does it make sense? Did you like it? Did you love it?

No matter if you like it or not, testing is essential. And tests generally involves mocking methods.

So if you make programs with Python and you don't know how to test your code, i recommend to you to start learning.

It's necessary.

How can I learn testing?

Come here. Come closer.

I'll teach you how.

gif-come-here

My plans with this repository is to to teach you me how to master on python fucking testing.

Credits