Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to unit test code that generates images?

What is the best way to unit test code that generates images? Say, for example, a class that generates a plot or a chart?

like image 295
epoch Avatar asked Aug 15 '10 14:08

epoch


People also ask

What are best practices for unit testing methods that use cache heavily?

If you want true Unit Tests, then you have to mock the cache: write a mock object that implements the same interface as the cache, but instead of being a cache, it keeps track of the calls it receives, and always returns what the real cache should be returning according to the test case.

Does unit test increase code quality?

Good unit tests create testable code, which improves quality. That code will have fewer defects, which means fewer bug fixes, for faster project completion.


2 Answers

If this class uses a third party library to generate plots/charts (say matplotlib) then you can write tests for the methods that generate input for the the library. This will be fairly easy.

If the output is an image and you are interested in verifying its properties then you will have to dig deeper. External image attributes (size, height, format etc.) can be easily verified but others such as the actual contents of the image would be quite hard. IMHO that wouldn't be worth the trouble.

If the output is non-binary (say SVG) then you can easily write tests to ensure that the output XML contains what you are looking for.

like image 79
Manoj Govindan Avatar answered Oct 03 '22 06:10

Manoj Govindan


A method that I've used is to generate a "known-good" file, store it in your source tree, and then do a binary compare against it as part of the test. If the file contents match the output hasn't changed.

This doesn't allow you to test all possible combinations of input that would generate the image, but is useful for basic regression tests.

like image 42
devstuff Avatar answered Oct 03 '22 06:10

devstuff