我正在為最近部署的 web 應用程式構建測驗套件。它是使用 flask-socketio 構建的,并使用 pytest 作為測驗套件。
這里的大問題是缺乏使用flask-socketio 進行測驗的檔案。我發現了一些包含測驗套件的專案:https : //github.com/miguelgrinberg/Flask-SocketIO/blob/main/test_socketio.py https://github.com/miguelgrinberg/flack/blob/master/tests/tests .py
但是這些都沒有對服務器對訊息的回應進行測驗。
就我而言,我的服務器中有以下偵聽器:
@socketio.on('getBettors', namespace='/coin')
def get_current_bettors_coin():
"""
functionshould send current tickets to the client to build
"""
game_name = "coinv1"
coin_game = Game.objects(game_name=game_name)[0]
current_time = get_utc_now_func()
current_game = GameSeed.objects(
game_id=coin_game.pk,
start_time__lte=current_time,
end_time__gt=current_time,
)[0]
current_game_tickets = GameTicket.objects(
game_id=current_game.pk
)
list_bets = []
for ticket in current_game_tickets:
ticket_dict = {
"user": User.objects(id=ticket.owner_id.pk)[0].username,
"choice": str(ticket.user_choice),
"value": str(ticket.bet_value),
}
list_bets.append(ticket_dict)
emit('getBettors', {"bets": list_bets}, broadcast=True)
基本上,聽眾搜索資料庫以獲取某個游戲中的所有當前投注者(這是一個投注游戲)
但是我無法測驗發出的結果是否是預期的實際結果,因為在 flask-socketio 測驗客戶端中沒有這樣的引數:
conftest.py
@pytest.fixture(scope='module')
def create_flask_app():
#drop all records in testDatabase before strting new test module
db = connect(host=os.environ["MONGODB_SETTINGS_TEST"], alias="testConnect")
for collection in db["testDatabase"].list_collection_names():
db["testDatabase"].drop_collection(collection)
db.close()
# Create a test client using the Flask application configured for testing
flask_app = create_app()
return flask_app
@pytest.fixture(scope='module')
def test_client(create_flask_app):
"""
Establish a test client for use within each test module
"""
with create_flask_app.test_client() as testing_client:
# Establish an application context
with create_flask_app.app_context():
yield testing_client # this is where the testing happens!
@pytest.fixture(scope='module')
def data_test_coin_toss_game():
"""
Populate DB with mock data for coin toss game tests
"""
#drop all records in testDatabase before strting new test class
db = connect(host=os.environ["MONGODB_SETTINGS_TEST"], alias="data_test_coin_toss_game")
mock_user_1 = User(
username = "data_test_coin_toss_game",
email = "[email protected]",
password = "sdgibgsdgsdg",
user_type = 1,
)
mock_user_1.create()
first_deposit = Transaction(
owner = mock_user_1,
transaction_type = "deposit funds",
currency_code = "MockCoin",
value = Decimal("1000.50"),
reference = "firstdeposit",
datetime = datetime.datetime.utcnow(),
)
first_deposit.save()
coin_game = Game(
game_name = "coinv1",
client_fixed_seed = hashlib.sha256("a random seed for the client".encode()).hexdigest(),
)
coin_game.save()
base_time = get_utc_now_func()
game_seed = GameSeed(
game_id = coin_game,
nonce = 4,
seed_crypto = hashlib.sha256("wow a secret seed".encode()).hexdigest(),
seed_client = hashlib.sha256("a random seed for the client".encode()).hexdigest(),
result = Decimal("0"),
start_time = base_time,
lock_time = base_time datetime.timedelta(days=1),
reveal_time = base_time datetime.timedelta(days=2),
end_time = base_time datetime.timedelta(days=3),
)
game_seed.save()
db.close()
測驗功能:
def test_get_bettors_websocket(create_flask_app, test_client, data_test_coin_toss_game):
"""
GIVEN a endpoint to retrieve all current bettors in a game
WHEN a user communicates to that endpoint
THEN check that the correct information is being sent out
"""
client = socketio.test_client(create_flask_app)
assert client.is_connected()
received_return = False
@client.on('getBettors', namespace='/coin')
def process_request():
print("AAA")
global received_return
received_return = True
client.emit('getBettors', namespace='/coin')
assert received_return
在這一點上,我只是想找出一種方法來檢查從服務器發出的訊息,而沒有實際測驗業務邏輯。
測驗產生以下錯誤:
FAILED tests/functional/test_coin_game.py::test_get_bettors_websocket - AttributeError: 'SocketIOTestClient' object has no attribute 'on'
顯然,測驗客戶端不允許注冊“on”監聽器。有誰知道如何測驗這樣的應用程式?
***理論上我可以將服務器端監聽器的所有業務邏輯封裝在一個不同的函式中,然后可以進行測驗并讓監聽器呼叫該函式。但這似乎很草率,容易出錯,并且對于其他事件偵聽器,客戶端訊息的內容用作查詢的引數,因此我需要按照我上面建議的方式進行測驗
uj5u.com熱心網友回復:
Flask-SocketIO 測驗客戶端不是真正的客戶端,您無法注冊事件處理程式。測驗客戶端記錄服務器發出的任何內容,并允許您的測驗對其進行檢查。例如,Flask-SocketIO 自己的單元測驗在此處執行此操作。
received = client.get_received()
self.assertEqual(len(received), 3)
self.assertEqual(received[0]['args'], 'connected')
self.assertEqual(received[1]['args'], '{}')
self.assertEqual(received[2]['args'], '{}')
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/389888.html
上一篇:PythonFlask(部署在Heroku上):ImportError:在Heroku上部署時無法從“werkzeug”匯入名稱“secure_filename”
