Doing a unittest on a simple player mod Class

OK, this took me forever to get right....  But if you want an example of a unit test for a class that has
attributes,  here it is.

Update:  At the bottom, an example of the test with a 'log' that will print the results of what the function modattack returned as a value

The Class code:


class Player(object):
def __init__ (self, STR, ATK):
self.STR = STR
self.ATK = ATK

def modattack(self):
# define the damage an attack will do based on a formula:
# use floor division to return a whole number
attack = (self.STR * self.ATK) // 2
return attack


and a unit test to make sure there is not a NONE for the return attack:


import unittest
from Player import Player



class TestPlayer(unittest.TestCase):

def test_modattack(self):

player1 = Player(60, 10)

self.assertIsNotNone(player1.modattack)


with import logging:  (the Stackoverflow I got the logger info from:)
https://stackoverflow.com/questions/7472863/pydev-unittesting-how-to-capture-text-logged-to-a-logging-logger-in-captured-o


import unittest
from Player import Player
import sys
import logging

# set an instance of logging
logger = logging.getLogger()
# set a level of the logger
logger.level = logging.DEBUG


class TestPlayer(unittest.TestCase):

def test_modattack(self):
# create an instance of the Player class
player1 = Player(63, 10)
# create a variable to hold the return value of running the modattack
results = player1.modattack()
# set an instance of the logging streamHandler
stream_handler = logging.StreamHandler(sys.stdout)
# use logger to add the sys.out from stream_handler
logger.addHandler(stream_handler)
try:
#Try blocks are awesome
print(f"{results}")
logging.getLogger().info(results)
finally:
# this will remove the stream_handler so you can reuse it in other tests
logger.removeHandler(stream_handler)
self.assertIsNotNone(player1.modattack)



Comments

Popular posts from this blog

playing with color in powershell python

JavaScript Ascii animation with while loops and console.log

playing with trigonometry sin in pygame