Python for .NET Developers 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 in real applications it's usually not sufficient. If you're testing just basic code it's fine
0:10
but we're actually testing things that work with databases and logs and there's a lot of stuff, a lot of dependencies at work
0:16
deep, down below that we can't even directly work with. But don't fear, pytest and Python have plenty to offer to solve this problem.
0:25
We have two things that we need we need to have some test data. If we're not going to get it from the database where are we going to get it?
0:31
So we created a test fixture to pass in this test guitar data and we want to mock out, temporarily redefine
0:39
what certain functions mean and what they do so that we can actually call them but they don't call the dependencies.
0:46
They go get redirected to something here like for our get guitars from DB where we're returnin' our test data.
0:53
So what we do is we pass mocker, as an argument and we have to have pytest_mock installed for this to work, of course.
1:01
Once we do that, we can then call mocker.patch give it the functions that we need it to work with we can just say log, we don't care about what you do
1:09
just don't crash, just let people call you and then for the get guitars from DB that has a return value we got to work with
1:16
so we pass our guitar data over to the mocker like that. And then, from thereon, we just proceed as normal basically continue with the test
1:25
as we had tried to write it in the first place but now, get guitars from DB and log no longer are working with our dependencies
1:32
they're just working with our mock data, our test data. Super simple, right? One thing that's worth noting that is not visible or apparent here
1:40
is there's no dependency injection there's no IoC container there's not even an open/closed principle at work.
1:48
That's because in Python it's more common to patch out methods like this. Rarely do it in production, but for testing
1:54
it's considered kind of the way to go. And also, it is much harder because /lib is not a class with a constructor;
2:01
/lib is simply a module, and it has functions, all right? So it's a little bit harder to create these natural seams like you do in C#.
2:08
We'll just pass stuff to the constructor although we could totally do it here it's just not that common
2:13
so this patch style is more likely what you'll see.