How to get Python Unit Tests to run inside of the Unreal Editor?

Hi all,

I am trying to test some Python code inside of the Unreal Editor. However I seem to be having some difficulty getting the python unittest module to run inside of the editor.

To ensure I can get unit tests to run correctly in the editor, I have copied an example test from A Gentle Introduction to Unit Testing in Python as below:

import unittest

# Our code to be tested

class Rectangle: def **init**(self, width, height): self.width = width self.height = height

def get_area(self):

return self.width * self.height

def set_width(self, width):

self.width = width

def set_height(self, height):

self.height = height

# The test based on unittest module

class TestGetAreaRectangle(unittest.TestCase): 
def test_run(self): rectangle = Rectangle(2, 3) 
self.assertEqual(rectangle.get_area(), 9, "incorrect area")

# run the test

if **name** == '**main**': 
unittest.main()

When I run this code in PyCharm, it works perfectly and gives me the below result:

Ran 1 test in 0.005s
FAILED (failures=1)
incorrect area
9 != 6
Expected :6
Actual   :9
<Click to see difference>
Traceback (most recent call last):
  File "C:\Users\Michael\Desktop\Python\Production\first_test.py", line 24, in test_run
    self.assertEqual(rectangle.get_area(), 9, "incorrect area")
AssertionError: 6 != 9 : incorrect area

However, when I try to import the test file or run the code directly in the Output Log window, no test takes place and I get the below error message:

LogPython: Error: ----------------------------------------------------------------------
LogPython: Error: Ran 0 tests in 0.000s
LogPython: Error: OK
LogPython: Error: Traceback (most recent call last):
LogPython: Error:   File "C:/Users/***/Desktop/Python/Testing/unit_test.py", line 29, in <module>
LogPython: Error:     unittest.main()
LogPython: Error:   File "F:\Epic Games\UE_4.27\Engine\Binaries\ThirdParty\Python3\Win64\lib\unittest\main.py", line 101, in __init__
LogPython: Error:     self.runTests()
LogPython: Error:   File "F:\Epic Games\UE_4.27\Engine\Binaries\ThirdParty\Python3\Win64\lib\unittest\main.py", line 273, in runTests
LogPython: Error:     sys.exit(not self.result.wasSuccessful())
LogPython: Error: SystemExit: False

What’s causing this error? Is there any way to resolve it?

1 Like

I have resolved this issue; altering the final line

unittest.main()

to

unittest.main(exit=False)

has resolved the error.

it seems that unittest.main() cannot load the TestCase in ue py, i write loader & runner explicit, it works well.

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(myTest)
    result = unittest.TextTestRunner(stream=sys.stdout, buffer=True).run(suite)