Advertisement

How do I test code that only calls other functions or that only draws to the screen

Started by September 29, 2017 12:24 AM
3 comments, last by Bregma 7 years, 2 months ago

Currently, I'm working on recreating connect four for a portfolio of simple games. I'm also writing unit tests for all the code I can. Some of my code functions though only call other functions, or only draw to the screen...


#EXAMPLES...

def draw_refresh_button_text(self):
	font = pygame.font.Font(None, 24)
	text = font.render("Refresh", True, self.black)
	self.displaysurf.blit(
		text, 
		(
			self.refresh_button_rect.centerx-self.refresh_button_rect.centerx/self.refresh_button_rect.y,
			self.refresh_button_rect.centery-self.refresh_button_rect.centery/self.refresh_button_rect.x
		)
	)
		
      
def draw_disks(self):
	for column in self.grid:
		for disk in column:
			pygame.draw.ellipse(self.displaysurf, disk['color'], disk['rect'])
            
#ONLY CALLS OTHER FUNCTIONS...
def get_input(self): 
	inputmanager.InputManager.get_events()
	inputmanager.InputManager.check_for_quit_event()
	inputmanager.InputManager.update_keyboard_key_state()
	inputmanager.InputManager.get_keyboard_input()
	inputmanager.InputManager.update_mouse_button_state()
	inputmanager.InputManager.get_mouse_input()

How would I go about writing tests for code like this?

Should code like this even be tested?

Should all code be tested?

I'm using the Python unittest module to test. The code here uses Pygame.

Personally, I would not test methods like this via unit tests ... because it is not a "contract" you are going to be committing to memory and counting on as you work through other areas of code.

But there is a strategy for testing this kind of thing that is very easy ... and it is good for other cases that do define contracts that matter more.

You would create a "mock"/test object of the input manager, and your mock version would do something like verify that each method was called once during the test, or even that they were called in order ... the methods wouldn't DO anything real in the mock object, they'd just track the calls.

Advertisement

Thanks for reply, I'll look more into mocking.

In Python is very easy to monkey-patch mock functions and objects so you can test without hitting actual system, network, database, or screen draw calls.  Mocking a method of a class by binding a lambda to a side_effect attribute of the MagicMock lets you get away with injecting captive test data into your system from the bottom and then verifying the results returned by your higher-level functions.

Also, thinking about how you're going to mock required dependencies helps you architect your code better.

 

Stephen M. Webb
Professional Free Software Developer

This topic is closed to new replies.

Advertisement