0

I'm writing a project in Python that needs to make heavy use of filesystem operations, including changing ownership of files. This means I will need to query the passwd and group databases in order to convert between string representations of users/groups and numeric uid/gids.

I want to write unit tests to cover the module that will handle filesystem operations. However, I don't see any way of guaranteeing that the user names/group names/uids/gids will be in the passwd and group databases at testing time.

I thought about getting around this by mocking the pwd and grp modules in my unit tests, however, this means that my unit tests will tightly coupled to the implementation of my module. I don't want to care whether my module uses the pwd and grp modules at all.

How can I write my unit tests so that my module thinks it can run chown operations, which requires mapping users to uids and groups to gids, regardless of the actual contents of the passwd and group databases?

(There is a separate, but similar, question here about unit testing on file system operations, but I believe there is already an SO question or two or three or four out there on this topic, so I won't ask it again here - unfortunately, most of the answers given rely on mocking the os module, thus coupling the tests and implementation.)

Community
  • 1
  • 1
jayhendren
  • 4,286
  • 2
  • 35
  • 59
  • Have you considered building a jail to run the test in? (This requires more than just chroot, obviously, but almost anything built on that—a FreeBSD jail, a Solaris container, a Docker container, a Linux 3 user namespace, etc.—should be sufficient.) – abarnert Oct 27 '14 at 21:30
  • 1
    I don't see a way to avoid this. In the end, you have to trust the OS in what it performs when you call certain functions on it (including error-handling of course). If you don't want to do test this via mocks to isolate yourself from your environment (for good reasons, as you state yourself), you then can only bite the bullet and provide such a controlled environment. Which would make this rather more integration-testish with quite a twist. So I'd personally go for a mock-and-work-in-occuring-problems approach. – deets Oct 27 '14 at 21:32
  • Yes, but that requires root privileges, and I would rather not force people to elevate their privileges just to test my package on a potential installation site. – jayhendren Oct 27 '14 at 21:32
  • @deets, you're right, and that seems like the approach with the fewest problems, but I'm really hoping that there is a way to avoid this - perhaps a Unix tool that mocks system calls in some way? It just seems like unit tests and system-level operations would be mixed so frequently that there should be a better solution out there. – jayhendren Oct 27 '14 at 21:35

0 Answers0