使用 pytest 了解测试功能

问题描述 投票:0回答:1

我正在创建可以由 pytest 执行的测试函数。我已经创建了一个并且通过了,但我需要测试我创建的每个函数,但不知道如何做到这一点。

我尝试过使用断言,但我所有的测试都失败了。我看过有关理解测试的视频,但我似乎无法掌握如何使用它。这是我到目前为止所拥有的:

import random

players = []
MAX_PLAYERS = 8

def main():
    print("Are you ready to Left, Right, Center Game!")
    print("----------------------------------------------------")
    print("Let's play!!!")
    print("----------------------------------------------------")
    money = bet()
    print("We are betting $"+str(money)+ " per person")
    number_of_people = get_people()
    number_of_people = int(number_of_people)
    get_names(number_of_people)
    print("All names have been entered, let's play")
    run_game(players)
    winners_money = money * number_of_people
    print(f"You won, " + str(winners_money))
    print("----------------------------------------------------")

def get_people():
    while True:
        try:
            number_of_people = int(input("How many people are playing? (3-8) "))
            if 3 <= number_of_people <= MAX_PLAYERS:
                return number_of_people
        except ValueError:
            pass

def get_names(number_of_people):
    for name in range(number_of_people):
        name = input("Name: ").strip().title()
        players.append({"name": name, "chips": 3})

def bet():
    while True:
        amount = input("How much would you like to bet? $")
        if amount.isdigit():
            amount = int(amount)
            if amount > 0:
                break
            else:
                print("Amount must be greater than 0.")
        else:
            print("Please enter a number. Number needs to be greater than 0")

    return amount

def run_game(players):
    chips = ["L", "R", "C", "🔴", "🔴", "🔴"]
    while True:
        for player in players:
            print(f"\n{player['name']}'s turn\n")
            if player["chips"] > 0:
                number_of_rolls = min(player["chips"], 3)
                rolls = []
                for _ in range(number_of_rolls):
                    action = random.choice(chips)
                    if action == "L":
                        left_player = players[(players.index(player) - 1) % len(players)]
                        left_player["chips"] += 1
                        rolls.append("L")
                    elif action == "R":
                        right_player = players[(players.index(player) + 1) % len(players)]
                        right_player["chips"] += 1
                        rolls.append("R")
                    elif action == "C":
                        player["chips"] -= 0
                        rolls.append("C")
                    elif action == "🔴":
                        player["chips"] += 1
                        rolls.append("🔴")
                    player["chips"] -= 1
                print(f"{player['name']} rolled: {', '.join(rolls)}")
            else:
                print(f"{player['name']} has no chips left. Skip turn.")
            print("\nCurrent chip counts:")
            for player in players:
                print(f"{player['name']}: {player['chips']}")
            print("----------------------------------------------------")
        remaining_players = [player for player in players if player["chips"] > 0]
        if len(remaining_players) == 1:  # Only one player remaining
            last_player = remaining_players[0]
            if "🔴" in rolls:  # Last player rolled dot, end the game
                print()
                print(f"{last_player['name']} rolled 🔴!!! The game is over.")
                print(f"{last_player['name']} won!!! CONGRATS!!!!!!")
                return
            else:
                print(f"{last_player['name']} has to roll 'dot' to end the game.")
                continue

if __name__ == "__main__":
    main()




from project import get_people, get_names, bet, run_game
import pytest

def main():
    test_get_number_of_people()
    test_get_names_of_players()
    test_get_bet()
    test_run_game()

def test_get_number_of_people():
    with pytest.raises(Exception):
        assert get_people("8") == 8
python pytest
1个回答
0
投票

您不应该将测试代码放入主代码中。让我们创建您的主文件如下。

import random

players = []
MAX_PLAYERS = 8

def main():
    print("Are you ready to Left, Right, Center Game!")
    print("----------------------------------------------------")
    print("Let's play!!!")
    print("----------------------------------------------------")
    money = bet()
    print("We are betting $"+str(money)+ " per person")
    number_of_people = get_people()
    number_of_people = int(number_of_people)
    get_names(number_of_people)
    print("All names have been entered, let's play")
    run_game(players)
    winners_money = money * number_of_people
    print(f"You won, " + str(winners_money))
    print("----------------------------------------------------")

def get_people():
    while True:
        try:
            number_of_people = int(input("How many people are playing? (3-8) "))
            if 3 <= number_of_people <= MAX_PLAYERS:
                return number_of_people
        except ValueError:
            pass

def get_names(number_of_people):
    for name in range(number_of_people):
        name = input("Name: ").strip().title()
        players.append({"name": name, "chips": 3})

def bet():
    while True:
        amount = input("How much would you like to bet? $")
        if amount.isdigit():
            amount = int(amount)
            if amount > 0:
                break
            else:
                print("Amount must be greater than 0.")
        else:
            print("Please enter a number. Number needs to be greater than 0")

    return amount

def run_game(players):
    chips = ["L", "R", "C", "🔴", "🔴", "🔴"]
    while True:
        for player in players:
            print(f"\n{player['name']}'s turn\n")
            if player["chips"] > 0:
                number_of_rolls = min(player["chips"], 3)
                rolls = []
                for _ in range(number_of_rolls):
                    action = random.choice(chips)
                    if action == "L":
                        left_player = players[(players.index(player) - 1) % len(players)]
                        left_player["chips"] += 1
                        rolls.append("L")
                    elif action == "R":
                        right_player = players[(players.index(player) + 1) % len(players)]
                        right_player["chips"] += 1
                        rolls.append("R")
                    elif action == "C":
                        player["chips"] -= 0
                        rolls.append("C")
                    elif action == "🔴":
                        player["chips"] += 1
                        rolls.append("🔴")
                    player["chips"] -= 1
                print(f"{player['name']} rolled: {', '.join(rolls)}")
            else:
                print(f"{player['name']} has no chips left. Skip turn.")
            print("\nCurrent chip counts:")
            for player in players:
                print(f"{player['name']}: {player['chips']}")
            print("----------------------------------------------------")
        remaining_players = [player for player in players if player["chips"] > 0]
        if len(remaining_players) == 1:  # Only one player remaining
            last_player = remaining_players[0]
            if "🔴" in rolls:  # Last player rolled dot, end the game
                print()
                print(f"{last_player['name']} rolled 🔴!!! The game is over.")
                print(f"{last_player['name']} won!!! CONGRATS!!!!!!")
                return
            else:
                print(f"{last_player['name']} has to roll 'dot' to end the game.")
                continue

if __name__ == "__main__":
    main()

然后,您需要按照pytest的要求创建另一个文件,将其命名为:test_my_game.py,在test_my_game.py中,您应该打开一个新进程并在其中运行您的game.py。您可以使用 lib pexpect 来派生一个子进程并与其通信。示例

import pexpect

child = pexpect.spawn("python3 <path to you game.py>")
child.expect ('Are you ready to Left, Right, Center Game!')
child.expect ('How much would you like to bet? $')
child.sendline("30")

最后进行测试

pytest test_my_game.py
© www.soinside.com 2019 - 2024. All rights reserved.