Python for the .NET developer Transcripts
Chapter: Testing
Lecture: Concept: Testing without dependencies

Login or purchase this course to watch this video and the rest of the course contents.
0:00 While our simple test was nice
0:02 in real applications it's usually not sufficient.
0:06 If you're testing just basic code it's fine
0:09 but we're actually testing things
0:10 that work with databases and logs
0:12 and there's a lot of stuff, a lot of dependencies at work
0:15 deep, down below that we can't even directly work with.
0:19 But don't fear, pytest and Python
0:22 have plenty to offer to solve this problem.
0:24 We have two things that we need
0:26 we need to have some test data.
0:28 If we're not going to get it from the database
0:29 where are we going to get it?
0:30 So we created a test fixture
0:32 to pass in this test guitar data
0:35 and we want to mock out, temporarily redefine
0:38 what certain functions mean and what they do
0:41 so that we can actually call them
0:43 but they don't call the dependencies.
0:45 They go get redirected to something here
0:47 like for our get guitars from DB
0:50 where we're returnin' our test data.
0:52 So what we do is we pass mocker, as an argument
0:55 and we have to have pytest_mock installed
0:58 for this to work, of course.
1:00 Once we do that, we can then call mocker.patch
1:03 give it the functions that we need it to work with
1:06 we can just say log, we don't care about what you do
1:08 just don't crash, just let people call you
1:10 and then for the get guitars from DB
1:13 that has a return value we got to work with
1:15 so we pass our guitar data over to the mocker like that.
1:19 And then, from thereon, we just proceed as normal
1:22 basically continue with the test
1:24 as we had tried to write it in the first place
1:26 but now, get guitars from DB and log
1:28 no longer are working with our dependencies
1:31 they're just working with our mock data, our test data.
1:34 Super simple, right? One thing that's worth noting
1:37 that is not visible or apparent here
1:39 is there's no dependency injection
1:41 there's no IoC container
1:44 there's not even an open/closed principle at work.
1:47 That's because in Python it's more common
1:49 to patch out methods like this.
1:50 Rarely do it in production, but for testing
1:53 it's considered kind of the way to go.
1:56 And also, it is much harder
1:57 because /lib is not a class with a constructor;
2:00 /lib is simply a module, and it has functions, all right?
2:03 So it's a little bit harder
2:05 to create these natural seams like you do in C#.
2:07 We'll just pass stuff to the constructor
2:10 although we could totally do it here
2:11 it's just not that common
2:12 so this patch style is more likely what you'll see.