Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Python code that relies on hardware

So I have some code which uses gphoto2 to capture some images and stuff, I figured the best way to test this would be to wrap the gphoto2 code in something like an if TESTING: then return fake data, else do the gphoto2 stuff.

Does anyone know how I would achieve this, I've tried googling some things but I've not had any luck with specifically detecting if unit tests are being run or not.

I'd assume it would be something like if unittest: but maybe there is a better way to do this altogether?

EDIT: So based on the comments and answers so far, I tried out the unittest.mock package, it didn't work as I'd hoped, let me explain.

If I have method A which calls the capture image method (method B), then saves the image and a few other bits. I've managed to mock method B so that it returns either the image or None, which works fine when I call method B specifically, but when I try to call method A, it doesn't use the mock of method B, it uses the actual method B.

How do I make method A use the mock method B?

like image 605
Cephlin Avatar asked Oct 15 '25 11:10

Cephlin


1 Answers

The mock package exists for this very reason.

It's a standalone, pip-installable package for Python 2; it has been incorporated into the standard library for Python versions >= 3.3 (as unittest.mock).

like image 186
chucksmash Avatar answered Oct 18 '25 07:10

chucksmash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!