A Testable Weather Client

Medium ⏱ 12 min 62% acceptance ★★★★★ 4.7
Hard-coding requests.get inside functions makes them untestable offline. Write class WeatherClient whose constructor accepts a getter callable (defaulting to requests.get); temperature(city) calls self.getter(...) with the city as a param and returns json()['temp']. Tests can now inject a fake getter.

Examples

Example 1
Input
WeatherClient(fake_get).temperature('Pune')
Output
the temp from the injected fake, no network
Explanation

The dependency is swappable — that is the whole point.

Constraints

  • getter defaults to requests.get.
  • temperature uses only self.getter.

Topics

APIsdependency injection

Companies

ThoughtworksAtlassianBrowserStack

Hints

Hint 1

Store the callable on self.

Hint 2

The default argument wires production behavior.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.