Skip to content

Commit

Permalink
Merge pull request #217 from jeffreykirchner/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
jeffreykirchner authored Oct 25, 2023
2 parents 16b9cf8 + a60e0c4 commit ee67893
Show file tree
Hide file tree
Showing 5 changed files with 237 additions and 86 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1211,7 +1211,7 @@ async def patch_harvest(self, event):
return

logger = logging.getLogger(__name__)
# logger.info(f"patch_harvest: {event}")
logger.info(f"patch_harvest: {event}")
error_message = []
status = "success"

Expand Down
1 change: 1 addition & 0 deletions main/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
from .test_subject_consumer import *
from .test_production import *
from .test_consumption import *
from .test_subject_consumer_patch import *
95 changes: 13 additions & 82 deletions main/tests/test_subject_consumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class TestSubjectConsumer(TestCase):
session_player_1 = None
communicator_subject = []
communicator_staff = None

def setUp(self):
sys._called_from_test = True
logger = logging.getLogger(__name__)
Expand All @@ -38,6 +38,11 @@ def setUp(self):
self.session = Session.objects.get(title="Test 1")
self.parameter_set_json = self.session.parameter_set.json()

async_to_sync(self.set_up_communicators)

def tearDown(self):
async_to_sync(self.close_communicators)

async def set_up_communicators(self):
'''
setup the socket communicators
Expand Down Expand Up @@ -83,7 +88,6 @@ async def set_up_communicators(self):

self.assertEquals(response['message']['message_type'],'get_session')

@pytest.mark.asyncio
async def start_session(self):
'''
start session and advance past instructions
Expand Down Expand Up @@ -121,14 +125,19 @@ async def start_session(self):

response = await self.communicator_staff.receive_json_from()

@pytest.mark.asyncio
async def close_communicators(self):
'''
close the socket communicators
'''
for i in self.communicator_subject:
await i.disconnect()
await self.communicator_staff.disconnect()

await self.communicator_staff.disconnect()

# for i in self.communicator_subject:
# del i

# del self.communicator_staff

@pytest.mark.asyncio
async def test_chat_group(self):
Expand All @@ -138,8 +147,6 @@ async def test_chat_group(self):
logger = logging.getLogger(__name__)
logger.info(f"called from test {sys._called_from_test}" )

await self.set_up_communicators()

#send chat
message = {'message_type' : 'chat',
'message_text' : {'text': 'How do you do?',"current_location":{"x":0,"y":0}},
Expand Down Expand Up @@ -182,83 +189,7 @@ async def test_chat_group(self):
message_data = response['message']['message_data']
self.assertEquals(message_data['status'],'success')
self.assertEquals(message_data['text'],'Hello?')

await self.close_communicators()

@pytest.mark.asyncio
async def test_harvest_patch(self):
'''
test harvest patch
'''

logger = logging.getLogger(__name__)
logger.info(f"called from test {sys._called_from_test}" )

await self.set_up_communicators()
await self.start_session()

patch_1 = self.parameter_set_json["parameter_set_patches_order"][0]

message = {'message_type' : 'patch_harvest',
'message_text' : {'patch_id': patch_1},
'message_target' : 'group',
}

#harvest first ring
await self.communicator_subject[0].send_json_to(message)

for i in self.communicator_subject:
response = await i.receive_json_from()
#logger.info(response)
message_data = response['message']['message_data']
self.assertEquals(message_data['status'],'success')
self.assertEquals(response['message']['message_type'],'update_patch_harvest')
self.assertEquals(message_data['harvest_amount'], 8)

#harvest again and fail
await self.communicator_subject[0].send_json_to(message)

for i in self.communicator_subject:
response = await i.receive_json_from()
#logger.info(response)
message_data = response['message']['message_data']
self.assertEquals(message_data['status'],'fail')
self.assertEquals(message_data['error_message'][0]['message'],'Wait until next period to harvest again.')

#harvest next ring
await self.communicator_subject[1].send_json_to(message)

for i in self.communicator_subject:
response = await i.receive_json_from()
#logger.info(response)
message_data = response['message']['message_data']
self.assertEquals(message_data['status'],'success')
self.assertEquals(response['message']['message_type'],'update_patch_harvest')
self.assertEquals(message_data['harvest_amount'], 4)

#harvest next ring
await self.communicator_subject[2].send_json_to(message)

for i in self.communicator_subject:
response = await i.receive_json_from()
#logger.info(response)
message_data = response['message']['message_data']
self.assertEquals(message_data['status'],'success')
self.assertEquals(response['message']['message_type'],'update_patch_harvest')
self.assertEquals(message_data['harvest_amount'], 2)

#harvest when empty fails
await self.communicator_subject[3].send_json_to(message)

for i in self.communicator_subject:
response = await i.receive_json_from()
logger.info(response)
message_data = response['message']['message_data']
self.assertEquals(message_data['status'],'fail')
self.assertEquals(message_data['error_message'][0]['message'],'The patch is empty.')

await self.close_communicators()




222 changes: 222 additions & 0 deletions main/tests/test_subject_consumer_patch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
'''
build test
'''

import logging
import sys
import pytest
import json
import multiprocessing
import asyncio

from channels.testing import WebsocketCommunicator
from channels.routing import URLRouter
from asgiref.sync import sync_to_async
from asgiref.sync import async_to_sync

from django.test import TestCase


from main.models import Session

from main.routing import websocket_urlpatterns

class TestSubjectConsumerPatch(TestCase):
fixtures = ['auth_user.json', 'main.json']

user = None
session = None
parameter_set_json = None
session_player_1 = None

def setUp(self):
sys._called_from_test = True
logger = logging.getLogger(__name__)

logger.info('setup tests')

self.session = Session.objects.get(title="Test 1")
self.parameter_set_json = self.session.parameter_set.json()

async def set_up_communicators(self, communicator_subject, communicator_staff):
'''
setup the socket communicators
'''
logger = logging.getLogger(__name__)

session_player = await self.session.session_players.afirst()

connection_path_staff = f"/ws/staff-session/{self.session.channel_key}/session-{self.session.id}/{self.session.channel_key}"

application = URLRouter(websocket_urlpatterns)

#subjects
async for i in self.session.session_players.all():
connection_path_subject = f"/ws/subject-home/{self.session.channel_key}/session-{self.session.id}/{i.player_key}"
communicator_subject.append(WebsocketCommunicator(application, connection_path_subject))

connected_subject, subprotocol_subject = await communicator_subject[-1].connect()
assert connected_subject

message = {'message_type': 'get_session',
'message_text': {"player_key" :str(i.player_key)}}

await communicator_subject[-1].send_json_to(message)
response = await communicator_subject[-1].receive_json_from()
# logger.info(response)

self.assertEquals(response['message']['message_type'],'get_session')
self.assertEquals(response['message']['message_data']['session_player']['id'], i.id)

#staff
communicator_staff = WebsocketCommunicator(application, connection_path_staff)
connected_staff, subprotocol_staff = await communicator_staff.connect()
assert connected_staff

# #get staff session
message = {'message_type': 'get_session',
'message_text': {"session_key" :str(self.session.session_key)}}

await communicator_staff.send_json_to(message)
response = await communicator_staff.receive_json_from()
#logger.info(response)

self.assertEquals(response['message']['message_type'],'get_session')

return communicator_subject, communicator_staff

async def start_session(self, communicator_subject, communicator_staff):
'''
start session and advance past instructions
'''
logger = logging.getLogger(__name__)

# #start session
message = {'message_type' : 'start_experiment',
'message_text' : {},
'message_target' : 'self', }

await communicator_staff.send_json_to(message)

for i in communicator_subject:
response = await i.receive_json_from()
self.assertEquals(response['message']['message_type'],'update_start_experiment')
message_data = response['message']['message_data']
self.assertEquals(message_data['value'],'success')

response = await communicator_staff.receive_json_from()

# #advance past instructions
message = {'message_type' : 'next_phase',
'message_text' : {},
'message_target' : 'self',}

await communicator_staff.send_json_to(message)

for i in communicator_subject:
response = await i.receive_json_from()
self.assertEquals(response['message']['message_type'],'update_next_phase')
message_data = response['message']['message_data']
self.assertEquals(message_data['value'],'success')

response = await communicator_staff.receive_json_from()

return communicator_subject, communicator_staff

async def close_communicators(self, communicator_subject, communicator_staff):
'''
close the socket communicators
'''
for i in communicator_subject:
await i.disconnect()

await communicator_staff.disconnect()

@pytest.mark.asyncio
async def test_harvest_patch(self):
'''
test harvest patch
'''

communicator_subject = []
communicator_staff = None

logger = logging.getLogger(__name__)
logger.info(f"called from test {sys._called_from_test}" )

communicator_subject, communicator_staff = await self.set_up_communicators(communicator_subject, communicator_staff)
communicator_subject, communicator_staff = await self.start_session(communicator_subject, communicator_staff)

patch_1 = self.parameter_set_json["parameter_set_patches_order"][0]

message = {'message_type' : 'patch_harvest',
'message_text' : {'patch_id': patch_1},
'message_target' : 'group',
}

#harvest first ring
await communicator_subject[0].send_json_to(message)

for i in communicator_subject:
response = await i.receive_json_from()
#logger.info(response)
message_data = response['message']['message_data']
self.assertEquals(message_data['status'],'success')
self.assertEquals(response['message']['message_type'],'update_patch_harvest')
self.assertEquals(message_data['harvest_amount'], 8)

#harvest again and fail
await communicator_subject[0].send_json_to(message)

for i in communicator_subject:
response = await i.receive_json_from()
#logger.info(response)
message_data = response['message']['message_data']
self.assertEquals(message_data['status'],'fail')
self.assertEquals(message_data['error_message'][0]['message'],'Wait until next period to harvest again.')

#harvest next ring
await communicator_subject[1].send_json_to(message)

for i in communicator_subject:
response = await i.receive_json_from()
#logger.info(response)
message_data = response['message']['message_data']
self.assertEquals(message_data['status'],'success')
self.assertEquals(response['message']['message_type'],'update_patch_harvest')
self.assertEquals(message_data['harvest_amount'], 4)

#harvest next ring
await communicator_subject[2].send_json_to(message)

for i in communicator_subject:
response = await i.receive_json_from()
#logger.info(response)
message_data = response['message']['message_data']
self.assertEquals(message_data['status'],'success')
self.assertEquals(response['message']['message_type'],'update_patch_harvest')
self.assertEquals(message_data['harvest_amount'], 2)

#harvest when empty fails
await communicator_subject[3].send_json_to(message)

for i in communicator_subject:
response = await i.receive_json_from()
logger.info(response)
message_data = response['message']['message_data']
self.assertEquals(message_data['status'],'fail')
self.assertEquals(message_data['error_message'][0]['message'],'The patch is empty.')

session_local = await Session.objects.values("world_state").aget(title="Test 1")

#check all patch levels are harvested
for key, value in session_local["world_state"]["patches"][str(patch_1)]["levels"].items():
self.assertEquals(value["harvested"], True)

await self.close_communicators(communicator_subject, communicator_staff)






3 changes: 0 additions & 3 deletions startup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ python manage.py migrate
echo "Install htop:"
apt-get -y install htop
echo "Install redis"
curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list
apt-get update
apt-get -y install redis
echo "Start Daphne:"
redis-server & daphne -b 0.0.0.0 _trade_gifts.asgi:application

0 comments on commit ee67893

Please sign in to comment.