Skip to content

Instantly share code, notes, and snippets.

@PurpleBooth
Last active June 27, 2020 18:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PurpleBooth/2f424f3e9b2c1cbef34d86afbbc1f44f to your computer and use it in GitHub Desktop.
Save PurpleBooth/2f424f3e9b2c1cbef34d86afbbc1f44f to your computer and use it in GitHub Desktop.
Mocking

Mocking Exercises

These are a few exercises to get used to using mocking.

Pairs

Take a list of array elements and group them.

[1, 2, 3, 4, 5]
[[1, 2], [3, 4], [5]]

Implement this using TDD and Mocks.

Adder

Consider the following example

import time


class ScoreTypeA:
    def score(self):
        result = 10
        # Complex Calculation
        time.sleep(100)
        return result

class ScoreTypeB:
    def score(self):
        result = 11
        # Complex Calculation
        time.sleep(100)
        return result
        
assert adder([ScoreTypeA(), ScoreTypeA(), ScoreTypeB()]) == 31

Write a function to add any object with a score function. Don't use the real ScoreTypeB objects, as the complex calculation they perform takes several hours.

Monkeys

Requests is a python library to make HTTP requests. This is how you make a HTTP Request using it.

import requests

r = requests.get("https://example.com/")
print(r.json())

Write a script to work out your current external IP address. Mock out the request

Tips

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment