Using io.StringIO in a Unit Test
00:00
I’ve mentioned that these StringIO
objects could be useful for writing unit tests for some of your functions. So let’s go ahead and write a unit test for the upcase_file_content()
function and mimic the file object using a StringIO
object so that you don’t actually need to work with a real file on disk.
00:19
So create a new file that I call test.py
00:23
and then I will import unittest
and from process
import upcase_file_content
. It’s called upcase_file_content()
.
00:59
Okay, so I have the basic structure for writing a unit test for this upcase_file_content()
function that lives in my process
module.
01:06
And now instead of needing to work with a real file, I want to create a StringIO
object that mimics a file and lives inside of memory just to make it easier for this test to run.
01:16 And also quicker than if I would have to deal with input-output operations on my disk.
01:22
So to do this, I will create, call it fake_file
again, because we’ve been working with that before and I’ll say StringIO
. Well, I need to first import the io
module.
01:34
So I’ll say import io
, and then here I can use io.StringIO
and pass it some text.
01:44
hello, world
in lowercase.
01:48
And now I want to say that I would expect, expect that string would be HELLO, WORLD
,
01:59
because I want my upcase_file_content()
function to upcase all the characters that are in that file.
02:07
And now I can self.assertEqual()
the output of upcase_file_content()
when passing it the fake_file
object should be the same as the expected uppercase HELLO, WORLD
. Alright, so this would be a quick test that uses io.StringIO
to mimic a file on disk that, let’s assume that usually upcase_file_content()
would work with files on disk, but you want to write a test for it that can run in all sorts of environments that maybe don’t necessarily have disk access.
02:43
Then you could do it like this. Let’s go ahead and check whether it works. python -m
unittest test.py
and you can see that it ran one test and the test passed.
02:58
So that’s great. You’ve created a unit test for your upcase_file_content()
function that works just in memory and doesn’t actually need to have access to any sort of file on disk.
03:11 Of course, this only works if your function expects a file object as an input and then only operates on that file object. If your function would take a path as an input and then do the file handling inside of the body, then this would work in that same way.
03:28 And in the next lesson, we’ll take a quick look at what you can do if you’re working with a function like that.
Become a Member to join the conversation.