How to check the correctness of functions that are used randomly?

There are some areas of applications (for example, GameDev) in which many functions must be created using random values ​​to output their results. One example is given below:

def generate_key(monster_key_drop_coef):
    key_letters = string.ascii_uppercase
    rand = random.random()
    if monster_key_drop_coef < rand:
        return None

    button = {}
    button["type"] = random.choice([1,2,3])
    button["letter"] = random.choice(key_letters)
    return button

This function generates an element drop based on several random operations. The problem arises if you want to automatically check the correctness of this function. The generated values ​​are not deterministic, and recording regression tests seems impossible.

My questions:

  • Is it possible to write useful regression tests for this type of function?
  • Is there a general approach for creating some other types of tests in this case?
+5
source
2

:

def test_generate_key():
    button_list = []
    for _ in range(1, 1000):
        button_list.append(generate_key(0.2))

    is_all_none = True
    is_not_none = False
    for key in button_list:
        is_all_none &= (key is None)
        is_not_none |= (key is not None)

    assert is_all_none == False
    assert is_not_none == True

, ( ) 99,999% . , 1000 . 0.2 - .

+3

( ). , "" .

, , . :

  • None dict "type" "letter".
  • , .

unittest, , 1 . , . , .

+2

All Articles