def handle(self, *args, **options): session_config_name = options["session_config_name"] num_participants = options["num_participants"] label = options['label'] create_session(session_config_name=session_config_name, num_participants=num_participants, label=label)
def handle(self, *args, **options): session_config_name = options["session_config_name"] num_participants = options["num_participants"] label = options['label'] create_session( session_config_name=session_config_name, num_participants=num_participants, label=label )
def test_with_session(self): participant_client = self.participant_client create_session( 'simple', num_participants=2, room_name=settings.ROOM_WITH_LABELS_NAME, ) participant_client.connect() self.assertEqual(participant_client.receive(), {'status': 'session_ready'})
def sleep_then_create_session(**kwargs): # hack: this sleep is to prevent locks on SQLite. This gives time to let # the page request finish before create_session is called, # because creating the session involves a lot of database I/O, which seems # to cause locks when multiple threads access at the same time. if settings.DATABASES['default']['ENGINE'].endswith('sqlite3'): time.sleep(5) create_session(**kwargs)
def test_with_session(self): participant_client = self.participant_client create_session( 'simple', num_participants=2, room_name=settings.ROOM_WITH_LABELS_NAME, ) participant_client.connect() self.assertEqual( participant_client.receive(), {'status': 'session_ready'} )
def setUp(self): self.browser = django.test.client.Client() create_session( 'single_player_game', num_participants=6, room_name='default', ) create_session( 'single_player_game', num_participants=6, room_name='anon', )
def setUp(self): self.browser = django.test.client.Client() self.default_session = create_session( 'simple', # make it 6 so that we can test if the participant is reassigned # if they open their start link again (1/6 chance) num_participants=6, room_name='default', ) self.anon_session = create_session( 'simple', num_participants=2, room_name='anon', )
def setUp(self): super().setUp() self.session_with_labels = create_session( 'simple', # make it 6 so that we can test if the participant is reassigned # if they open their start link again (1/6 chance) num_participants=6, room_name=settings.ROOM_WITH_LABELS_NAME, ) self.session_without_labels = create_session( 'simple', num_participants=2, room_name=settings.ROOM_WITHOUT_LABELS_NAME, )
def create_session(self): client = TolokaClient(sandbox=False) if client.pool_exists(self.pool_id): logger.info(f'Pool {self.pool_id} exists') else: logger.warning(f'Pool {self.pool_id} *DOES NOT* exist') return pool_data = client.get_assignments(self.pool_id) items = pool_data.get('items', []) s = create_session('corr', num_participants=len(items)) logger.info( f'Session "{s.code}" was created for {len(items)} participants') ps = s.get_participants() for i, p in enumerate(ps): p.label = items[i].get('id') p.payoff = random.randint(1, 10) / 100 print(f'gonna pay them {p.payoff}') Participant.objects.bulk_update(ps, fields=['label', 'payoff']) if s.vars.get('toloka_pool_id'): logger.warning('Session was already linked. Going to override') s.vars['toloka_pool_id'] = self.pool_id s.save() logger.info( f'Session "{s.code}" and pool "{self.pool_id}" are linked now.')
def setUp(self): session = create_session('skip_wait_page', num_participants=2) bots = [] for participant in session.get_participants(): bot = ParticipantBot(participant, load_player_bots=False) bots.append(bot) self.bots = bots
def handle(self, *args, **options): redis_conn = get_redis_conn() otree.bots.browser.redis_flush_bots(redis_conn) worker = otree.bots.browser.Worker(redis_conn) session = create_session('misc_3p', num_participants=30) #participant_codes = session.participant_set.values_list('code', flat=True) worker.initialize_session(session_pk=session.pk)
def test_has_session_but_missing_hash(self): create_session( 'simple', # make it 6 so that we can test if the participant is reassigned # if they open their start link again (1/6 chance) num_participants=1, room_name=settings.ROOM_WITH_SECURE_URLS_NAME, ) url_without_hash = add_params_to_url(URL_PARTICIPANT_SECURE_URLS, {'participant_label': LABEL_REAL}) br = self.browser br.visit(url_without_hash) self.assertEqual(br.status_code, 404)
def test_edit_session_config(self): session_config_name = 'simple' config_key = 'use_browser_bots' session_config = SESSION_CONFIGS_DICT[session_config_name] original_config_value = session_config[config_key] new_config_value = not original_config_value session = create_session( 'simple', num_participants=1, edited_session_config_fields={config_key: new_config_value}) self.assertEqual(session.config[config_key], new_config_value) # make sure it didn't affect the value for future sessions # (this bug occurred because we mutated the dictionary) session2 = create_session( 'simple', num_participants=1) self.assertEqual(session2.config[config_key], original_config_value)
def test_edit_session_config(self): session_config_name = 'simple' config_key = 'use_browser_bots' session_config = SESSION_CONFIGS_DICT[session_config_name] original_config_value = session_config[config_key] new_config_value = not original_config_value session = create_session( 'simple', num_participants=1, edited_session_config_fields={config_key: new_config_value}) self.assertEqual(session.config[config_key], new_config_value) # make sure it didn't affect the value for future sessions # (this bug occurred because we mutated the dictionary) session2 = create_session('simple', num_participants=1) self.assertEqual(session2.config[config_key], original_config_value)
def setUp(self): session = create_session(self.config_name, num_participants=2) self.p1, self.p2 = session.get_participants() #path = channel_utils.wait_page_path( # session.pk, group_id_in_subsession=1, index_in_pages=self.wait_page_index) #self.p1_client = ConnectingWSClient(path=path) self.br = splinter.Browser('django')
def test_has_session_but_missing_hash(self): create_session( 'simple', # make it 6 so that we can test if the participant is reassigned # if they open their start link again (1/6 chance) num_participants=1, room_name=settings.ROOM_WITH_SECURE_URLS_NAME, ) url_without_hash = add_params_to_url( URL_PARTICIPANT_SECURE_URLS, {'participant_label': LABEL_REAL} ) br = self.browser br.visit(url_without_hash) self.assertEqual(br.status_code, 404)
def post(self, request, format=None): try: data = self.request.data print(data['session_type_name']) session = create_session(session_config_name=data['session_type_name'], label=data['label'] or '',num_participants=data['num_participants']) return Response(session.code, status=status.HTTP_200_OK) # return Response(getSerializableObject(session, False), status=status.HTTP_200_OK)#Get entire session object except Exception as e: return Response(e.message, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def inner_post(self, **kwargs): session = create_session(**kwargs) room_name = kwargs.get('room_name') if room_name: channel_utils.sync_group_send_wrapper( type='room_session_ready', group=channel_utils.room_participants_group_name(room_name), event={}, ) return HttpResponse(session.code)
def test_animals_can_speak(self): """Animals that can speak are correctly identified""" print(f'TOTSESSIONS: {Session.objects.all().count()}') cities = [(f"{x:02d}") for x in range(1, 13)] sessions = [ create_session(session_config_name='trust_demo_ru', num_participants=2, modified_session_config_fields=dict(city_code=x)) for x in cities ] self.TestCreateSession() m = MegaSession.objects.all().first() # MingleSession.objects.all().update(megasession=m) # parts = Participant.objects.filter(session__in=sessions) # megapars = [MegaParticipant(owner=i, megasession=m) for i in parts] # MegaParticipant.objects.bulk_create(megapars) tps = Player.objects.filter(session__in=sessions) tps.update(calculable=True) tps = Player.objects.filter(session__in=sessions) evens = tps.annotate(odd=F('id') % 2).filter(odd=False) odds = tps.annotate(odd=F('id') % 2).filter(odd=True) odds.update(_role='sender') evens.update(_role='receiver') print(MegaParticipant.objects.all().count()) m.form_groups() senders = Player.objects.filter(_role='sender') receivers = Player.objects.filter(_role='receiver') ps = Player.objects.filter(session__in=sessions) for p in ps: p.create_decisions() p.create_beliefs() upd_decisions = [] for d in Decision.objects.filter(decision_type='sender_decision'): d.answer = random.choice([0, 10]) upd_decisions.append(d) for d in Decision.objects.filter(decision_type='return_decision'): d.answer = random.choice(Constants.receiver_choices) upd_decisions.append(d) for d in Decision.objects.filter(decision_type='receiver_belief'): d.answer = random.choice([0, 10]) upd_decisions.append(d) for d in Decision.objects.filter(decision_type='sender_belief'): d.answer = random.choice(Constants.receiver_choices) upd_decisions.append(d) Decision.objects.bulk_update(upd_decisions, ['answer']) for p in Participant.objects.all(): print("BEFOREBPAYOFF", p.payoff) m.calculate_payoffs() for p in Participant.objects.all(): print("AFTERBPAYOFF", p.payoff)
def handle(self, *args, **options): session_config_name = options["session_config_name"] num_participants = options["num_participants"] label = options['label'] session = create_session( session_config_name=session_config_name, num_participants=num_participants, label=label) print("Created session with code: {}".format(session.code)) print("")
def handle(self, *args, **options): session_config_name = options["session_config_name"] num_participants = options["num_participants"] label = options['label'] session = create_session(session_config_name=session_config_name, num_participants=num_participants, label=label) print("Created session with code: {}".format(session.code)) print("")
def setUp(self): session = create_session( session_config_name='timeout_submission', num_participants=1, ) self.participant = session.get_participants()[0] # simulate opening the start link in the most minimal way # a more heavyweight approach would be to create the ParticipantBot # and open the start URL self.participant._index_in_pages = 1 self.participant.save()
def runTest(self): logger.info("Creating '{}' session".format(self.session_name)) sssn = session.create_session( session_config_name=self.session_name, special_category=constants_internal.session_special_category_bots) sssn.label = '{} [bots]'.format(self.session_name) sssn.save() # since players are assigned to groups in a background thread, # we need to wait for that to complete. logger.info("Adding bots on session '{}'".format(self.session_name)) while True: sssn = otree.models.Session.objects.get(id=sssn.pk) if sssn._ready_to_play: break time.sleep(1) msg = "'GET' over first page of all '{}' participants" logger.info(msg.format(self.session_name)) participant_bots = [] for participant in sssn.get_participants(): participant_bot = ParticipantBot(participant) participant_bots.append(participant_bot) participant_bot.start() submit_groups = self.zip_submits(participant_bots) pending = PendingBuffer() while pending or submit_groups: seen_pending_bots = set() for submit, attempts in pending: if attempts > MAX_ATTEMPTS: msg = "Max attepts reached in submit '{}'" raise AssertionError(msg.format(submit)) if submit.bot not in seen_pending_bots and submit.execute(): pending.remove(submit) else: seen_pending_bots.add(submit.bot) group = submit_groups.pop(0) if submit_groups else () for submit in group: if submit is None: continue if pending.is_blocked(submit) or not submit.execute(): pending.add(submit) logger.info("Stopping bots") for bot in participant_bots: bot.stop()
def runTest(self): logger.info("Creating '{}' session".format(self.session_name)) sssn = session.create_session( session_config_name=self.session_name, special_category=constants_internal.session_special_category_bots) sssn.label = '{} [bots]'.format(self.session_name) sssn.save() # since players are assigned to groups in a background thread, # we need to wait for that to complete. logger.info("Adding bots on session '{}'".format(self.session_name)) while True: sssn = otree.models.Session.objects.get(id=sssn.pk) if sssn._ready_to_play: break time.sleep(1) msg = "'GET' over first page of all '{}' participants" logger.info(msg.format(self.session_name)) participant_bots = [] for participant in sssn.get_participants(): participant_bot = ParticipantBot(participant) participant_bots.append(participant_bot) participant_bot.start() submit_groups = self.zip_submits(participant_bots) pending = PendingBuffer() while pending or submit_groups: seen_pending_boots = set() for submit, attempts in pending: if attempts > MAX_ATTEMPTS: msg = "Max attepts reached in submit '{}'" raise AssertionError(msg.format(submit)) if submit.bot not in seen_pending_boots and submit.execute(): pending.remove(submit) else: seen_pending_boots.add(submit.bot) group = submit_groups.pop(0) if submit_groups else () for submit in group: if submit is None: continue if pending.is_blocked(submit) or not submit.execute(): pending.add(submit) logger.info("Stopping bots") for bot in participant_bots: bot.stop()
def setUp(self): session = create_session( session_config_name='timeout_submission', num_participants=1, use_cli_bots=True, ) self.participant = session.get_participants()[0] # simulate opening the start link in the most minimal way # a more heavyweight approach would be to create the ParticipantBot # and open the start URL self.participant._index_in_pages = 1 self.participant.save()
def ensure_enough_spare_sessions(session_config_name): # hack: this sleep is to prevent locks on SQLite. This gives time to let # the page request finish before create_session is called, because creating # the session involves a lot of database I/O, which seems to cause locks # when multiple threads access at the same time. if settings.DATABASES['default']['ENGINE'].endswith('sqlite3'): time.sleep(5) spare_sessions = Session.objects.filter( special_category=constants.session_special_category_demo, demo_already_used=False, ) spare_sessions = [ s for s in spare_sessions if s.config['name'] == session_config_name ] # fill in whatever gap exists. want at least 3 sessions waiting. for i in range(MAX_SESSIONS_TO_CREATE - len(spare_sessions)): create_session( special_category=constants.session_special_category_demo, session_config_name=session_config_name, )
def handle(self, session_config_name, num_participants, label, room_name, **kwargs): session = create_session(session_config_name=session_config_name, num_participants=num_participants, label=label) if room_name: room = ROOM_DICT[room_name] room.set_session(session) logger.info("Created session with code {} in room '{}'\n".format( session.code, room_name)) else: logger.info("Created session with code {}\n".format(session.code))
def test_customization(self): # need 2 participants so the wait page is not skipped session = create_session('waitpage_template', num_participants=2) participant = session.participant_set.first() br = splinter.Browser('django') Constants = tests.waitpage_template.models.Constants with self.assertTemplateUsed(template_name=Constants.wait_page_template): br.visit(participant._start_url()) for substring in [ Constants.custom_title_text, Constants.custom_body_text, ]: self.assertTrue(br.is_text_present(substring))
def handle(self, *args, **options): session_config_name = options["session_config_name"] num_participants = options["num_participants"] label = options['label'] session = create_session( session_config_name=session_config_name, num_participants=num_participants, label=label) if options['room']: room = ROOM_DICT[options['room']] room.set_session(session) logger.info("Created session with code {} in room '{}'\n".format( session.code, options['room'])) else: logger.info("Created session with code {}\n".format(session.code))
def handle(self, *args, **options): session_config_name = options["session_config_name"] num_participants = options["num_participants"] label = options['label'] session = create_session(session_config_name=session_config_name, num_participants=num_participants, label=label) if options['room']: room = ROOM_DICT[options['room']] room.set_session(session) logger.info("Created session with code {} in room '{}'\n".format( session.code, options['room'])) else: logger.info("Created session with code {}\n".format(session.code))
def session_creator(num_participants, stub): cities = City.objects.all().order_by('code') for x in cities: logger.info( f'Creating session for city: {x.eng}; participants:{num_participants} ' ) s = create_session(session_config_name='full_ru', num_participants=num_participants, label=f'{stub}: {x.eng}', modified_session_config_fields=dict( city_code=x.code, toloka=True, toloka_sandbox=False, )) s.comment = s.label s.save()
def inner_post(self, num_participants, session_config_name, case_number, pre_create_id): session = create_session(session_config_name=session_config_name, num_participants=num_participants) otree.bots.browser.initialize_session(session_pk=session.pk, case_number=case_number) BrowserBotsLauncherSessionCode.objects.update_or_create( # i don't know why the update_or_create arg is called 'defaults' # because it will update even if the instance already exists # maybe for consistency with get_or_create defaults=dict(code=session.code, pre_create_id=pre_create_id)) channel_utils.sync_group_send_wrapper(type='browserbot_sessionready', group='browser_bot_wait', event={}) return HttpResponse(session.code)
def post(self, request, *args, **kwargs): num_participants = int(request.POST['num_participants']) session_config_name = request.POST['session_config_name'] bot_case_number = int(request.POST['bot_case_number']) session = create_session(session_config_name=session_config_name, num_participants=num_participants, bot_case_number=bot_case_number, force_browser_bots=True) BrowserBotsLauncherSessionCode.objects.update_or_create( # i don't know why the update_or_create arg is called 'defaults' # because it will update even if the instance already exists # maybe for consistency with get_or_create defaults={'code': session.code}) channels.Group('browser_bot_wait').send( {'text': json.dumps({'status': 'session_ready'})}) return HttpResponse(session.code)
def inner_post(self, **kwargs): ''' Notes: - This allows you to pass parameters that did not exist in the original config, as well as params that are blocked from editing in the UI, either because of datatype. I can't see any specific problem with this. ''' session = create_session(**kwargs) room_name = kwargs.get('room_name') if room_name: channel_utils.sync_group_send_wrapper( type='room_session_ready', group=channel_utils.room_participants_group_name(room_name), event={}, ) return HttpResponse(session.code)
def post(self, request): num_participants = int(request.POST['num_participants']) session_config_name = request.POST['session_config_name'] case_number = int(request.POST['case_number']) session = create_session(session_config_name=session_config_name, num_participants=num_participants) otree.bots.browser.initialize_session(session_pk=session.pk, case_number=case_number) BrowserBotsLauncherSessionCode.objects.update_or_create( # i don't know why the update_or_create arg is called 'defaults' # because it will update even if the instance already exists # maybe for consistency with get_or_create defaults={'code': session.code}) channel_utils.sync_group_send_wrapper(type='browserbot_sessionready', group='browser_bot_wait', event={}) return HttpResponse(session.code)
def data_creator(num_participants): for i in settings.CITIES: City.objects.get_or_create(code=i['code'], defaults={'description': i['name'], 'eng': i['eng']}) cities = [(f"{x:02d}") for x in range(1, 13)] sessions = [] for x in cities: logger.info(f'Creating session for city: {x}; participants:{num_participants} ') s = create_session( session_config_name='trust_ru', num_participants=num_participants, label=x, modified_session_config_fields=dict(city_code=x) ) sessions.append(s) tps = Player.objects.filter(session__in=sessions) tps.update(calculable=True) tps = Player.objects.filter(session__in=sessions) evens = tps.annotate(odd=F('id') % 2).filter(odd=False) odds = tps.annotate(odd=F('id') % 2).filter(odd=True) odds.update(_role='sender') evens.update(_role='receiver') upd_decisions = [] ds = Decision.objects.filter(owner__session__in=sessions) for d in ds.filter(decision_type='sender_decision', owner___role='sender'): d.answer = random.choice([0, 10]) upd_decisions.append(d) for d in ds.filter(decision_type='return_decision', owner___role='receiver'): d.answer = random.choice([12, 15, 18]) upd_decisions.append(d) for d in ds.filter(decision_type='receiver_belief', owner___role='receiver'): d.answer = random.choice([0, 10]) upd_decisions.append(d) for d in ds.filter(decision_type='sender_belief', owner___role='sender'): d.answer = random.choice([12, 15, 18, 21]) upd_decisions.append(d) generate_rest(sessions, upd_decisions)
def post(self, request, *args, **kwargs): num_participants = int(request.POST['num_participants']) session_config_name = request.POST['session_config_name'] bot_case_number = int(request.POST['bot_case_number']) session = create_session( session_config_name=session_config_name, num_participants=num_participants, bot_case_number=bot_case_number, force_browser_bots=True ) BrowserBotsLauncherSessionCode.objects.update_or_create( # i don't know why the update_or_create arg is called 'defaults' # because it will update even if the instance already exists # maybe for consistency with get_or_create defaults={'code': session.code} ) channels.Group('browser_bot_wait').send( {'text': json.dumps({'status': 'session_ready'})} ) return HttpResponse(session.code)
def run_bots(session_config_name, num_participants): session = create_session( session_config_name, num_participants=num_participants, use_cli_bots=True) bot_runner = session_bot_runner_factory(session) bot_runner.play()
def setUp(self): session = create_session('i18n', num_participants=1, use_cli_bots=True) self.bot_runner = session_bot_runner_factory(session)
def setUp(self): session = create_session( 'wait_page', num_participants=4, use_cli_bots=True) subsession = session.get_subsessions()[0] self.group1 = subsession.get_groups()[0]
def setUp(self): session = create_session('simple', num_participants=1) self.session_id = session.id self.player_id = simple_models.Player.objects.get( session_id=self.session_id).id
def setUp(self): create_session( session_config_name='timeout_submission', num_participants=1, use_cli_bots=True, )
def run_bots(session_config_name, num_participants): session = create_session(session_config_name, num_participants=num_participants, use_cli_bots=True) bot_runner = session_bot_runner_factory(session) bot_runner.play()