-1

I have made a python project by following a tutorial on youtube. Now, I want to write unit test to test one of it's function get_slot_machine_spin()

def get_slot_machine_spin(rows, cols, symbols):
    all_symbols = []
    for symbol, symbol_count in symbols.items():
        for _ in range(symbol_count):
            all_symbols.append(symbol)

    columns = []
    for _ in range(cols):
        column = []
        current_symbols = all_symbols[:] 
        for _ in range(rows):
            value = random.choice(current_symbols)
            current_symbols.remove(value)
            column.append(value)

        columns.append(column)

    return columns

But, the function use random.choice in it. It returns a list with randomly generated characters. And I'm not sure how can I write a test for that.

This is the source code of the project.

Rylie
  • 19
  • 4
  • @DavisHerring I did checked that one before. But, as a beginner I was not abe to unterstand a lot of things. – Rylie Oct 03 '22 at 08:26

1 Answers1

0

One thing you could do is pass in the function which will be used to generate random values as an argument. That way, when you want to test it, you can tell it exactly what you want it to generate. You can then test the behaviour of your function using predictable values.

Something like (I'm not writing much python these days):

import random

def my_function (min, max, generate_random):
  number = generate_random(min, max)
  
  if (number < min):
    return "Invalid"
  
  if (number > max):
    return "Invalid"
  
  return "The number is: %s" % number


print(my_function(0, 3, random.randint))

def always(n):
  return lambda x, _: n

def it_uses_the_value_from_provided_generator_function():
  result = my_function(0, 3, always(3))
  if not result:
    print("FAILED TEST")
  else:
    print("PASSED TEST")
    
it_uses_the_value_from_provided_generator_function()
OliverRadini
  • 6,238
  • 1
  • 21
  • 46