On Thu, Jan 28, 2016 at 12:44 AM, Alan Gauld <alan.ga...@btinternet.com> wrote: > On 28/01/16 04:23, boB Stepp wrote: > >> I don't want to mess with what will become the program's *real* >> classifiers.txt (And other needed text files to come, that will >> likewise be editable.), so how do I simulate these various needed file >> operations in a way that tests the actual program code, but without >> touching the actual data files? > > Danny has shown you one way using a mocked filesystem. > But for your case can't you just specify a file location > as an environment variable or argv? That way you get the > advantage of using real files, which can be an important > factor in timing issues, especially if you plan on having > any concurrency going on. And it's simple to do...
Just to emphasize what I think is an essential point: the basic approach we're doing is here parameterization: to take something that used to be hardcoded, and turn it into a parameter that allows us to substitute with something else. As Alan says, you can also parameterize in a different way: by the directory location where files are being read. Then you can use a temporary directory for your unit tests, and prepare the testing environment that way. If you take this approach, the tempfile module can help with this. https://docs.python.org/3.5/library/tempfile.html https://docs.python.org/3.5/library/tempfile.html#tempfile.TemporaryDirectory The mocking approach is one where we're doing this parameterization at a behavioral level. When we started to program, we may have initially thought that a parameter could only be numbers, since that's what algebra traditionally uses as its domain. When we program, we find that domain of values expanded to a richer set, and not just to inactive values like strings or dictionaries or images, but now we can pass entire collections of behavior as a parameter. That's one of the lessons of OOP: values are not just inert data: they can define dynamic behavior. (Aside: this is somewhat why I think the topic of inheritance and inheritance hierarchies are entirely the wrong things to focus on when we're teaching OOP. Those topics are often used as a shortcut mechanism to do code sharing, and although that's convenient, my opinion is that it misses the forest for the trees. What I think OOP's heart is beating is in the ability to parameterize behavior.) _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor