def test_get_all_users(self): """ Test getting all authors for a course where their permissions run the gamut of allowed group types. """ # first check the course creator.has explicit access (don't use has_access as is_staff # will trump the actual test) self.assertTrue(CourseInstructorRole(self.course_key).has_user(self.user), "Didn't add creator as instructor.") users = copy.copy(self.users) # doesn't use role.users_with_role b/c it's verifying the roles.py behavior user_by_role = {} # add the misc users to the course in different groups for role in [CourseInstructorRole, CourseStaffRole, OrgStaffRole, OrgInstructorRole]: user_by_role[role] = [] # Org-based roles are created via org name, rather than course_key if (role is OrgStaffRole) or (role is OrgInstructorRole): group = role(self.course_key.org) else: group = role(self.course_key) # NOTE: this loop breaks the roles.py abstraction by purposely assigning # users to one of each possible groupname in order to test that has_course_access # and remove_user work user = users.pop() group.add_users(user) user_by_role[role].append(user) self.assertTrue(has_course_access(user, self.course_key), "{} does not have access".format(user)) course_team_url = reverse_course_url("course_team_handler", self.course_key) response = self.client.get_html(course_team_url) for role in [CourseInstructorRole, CourseStaffRole]: # Global and org-based roles don't appear on this page for user in user_by_role[role]: self.assertContains(response, user.email) # test copying course permissions copy_course_key = SlashSeparatedCourseKey("copyu", "copydept.mycourse", "myrun") for role in [CourseInstructorRole, CourseStaffRole, OrgStaffRole, OrgInstructorRole]: if (role is OrgStaffRole) or (role is OrgInstructorRole): auth.add_users(self.user, role(copy_course_key.org), *role(self.course_key.org).users_with_role()) else: auth.add_users(self.user, role(copy_course_key), *role(self.course_key).users_with_role()) # verify access in copy course and verify that removal from source course w/ the various # groupnames works for role in [CourseInstructorRole, CourseStaffRole, OrgStaffRole, OrgInstructorRole]: for user in user_by_role[role]: # forcefully decache the groups: premise is that any real request will not have # multiple objects repr the same user but this test somehow uses different instance # in above add_users call if hasattr(user, "_roles"): del user._roles self.assertTrue(has_course_access(user, copy_course_key), "{} no copy access".format(user)) if (role is OrgStaffRole) or (role is OrgInstructorRole): auth.remove_users(self.user, role(self.course_key.org), user) else: auth.remove_users(self.user, role(self.course_key), user) self.assertFalse(has_course_access(user, self.course_key), "{} remove didn't work".format(user))
def test_get_all_users(self): """ Test getting all authors for a course where their permissions run the gamut of allowed group types. """ # first check the course creator.has explicit access (don't use has_access as is_staff # will trump the actual test) self.assertTrue( CourseInstructorRole(self.course_key).has_user(self.user), "Didn't add creator as instructor.") users = copy.copy(self.users) # doesn't use role.users_with_role b/c it's verifying the roles.py behavior user_by_role = {} # add the misc users to the course in different groups for role in [CourseInstructorRole, CourseStaffRole]: user_by_role[role] = [] # pylint: disable=protected-access group = role(self.course_key) # NOTE: this loop breaks the roles.py abstraction by purposely assigning # users to one of each possible groupname in order to test that has_course_access # and remove_user work user = users.pop() group.add_users(user) user_by_role[role].append(user) self.assertTrue(has_course_access(user, self.course_key), "{} does not have access".format(user)) course_team_url = reverse_course_url('course_team_handler', self.course_key) response = self.client.get_html(course_team_url) for role in [CourseInstructorRole, CourseStaffRole]: for user in user_by_role[role]: self.assertContains(response, user.email) # test copying course permissions copy_course_key = SlashSeparatedCourseKey('copyu', 'copydept.mycourse', 'myrun') for role in [CourseInstructorRole, CourseStaffRole]: auth.add_users(self.user, role(copy_course_key), *role(self.course_key).users_with_role()) # verify access in copy course and verify that removal from source course w/ the various # groupnames works for role in [CourseInstructorRole, CourseStaffRole]: for user in user_by_role[role]: # forcefully decache the groups: premise is that any real request will not have # multiple objects repr the same user but this test somehow uses different instance # in above add_users call if hasattr(user, '_roles'): del user._roles self.assertTrue(has_course_access(user, copy_course_key), "{} no copy access".format(user)) auth.remove_users(self.user, role(self.course_key), user) self.assertFalse(has_course_access(user, self.course_key), "{} remove didn't work".format(user))
def test_notifications_handler_dismiss(self): state = CourseRerunUIStateManager.State.FAILED should_display = True rerun_course_key = CourseLocator(org='testx', course='test_course', run='test_run') # add an instructor to this course user2 = UserFactory() add_instructor(rerun_course_key, self.user, user2) # create a test notification rerun_state = CourseRerunState.objects.update_state(course_key=rerun_course_key, new_state=state, allow_not_found=True) CourseRerunState.objects.update_should_display(entry_id=rerun_state.id, user=user2, should_display=should_display) # try to get information on this notification notification_dismiss_url = reverse_course_url('course_notifications_handler', self.course.id, kwargs={ 'action_state_id': rerun_state.id, }) resp = self.client.delete(notification_dismiss_url) self.assertEquals(resp.status_code, 200) with self.assertRaises(CourseRerunState.DoesNotExist): # delete nofications that are dismissed CourseRerunState.objects.get(id=rerun_state.id) self.assertFalse(has_course_access(user2, rerun_course_key))
def experiments_handler(request, course_key_string): """ Displays the experiment list for the current course :param request: http request default :param course_key_string: slashes:USPx+CS0000+2014_1 :return: rendered html Mostra a listagem dos experimentos deste curso. :param request: http request default :param course_key_string: slashes:USPx+CS0000+2014_1 :return: html renderizado """ usage_key = CourseKey.from_string(course_key_string) if not has_course_access(request.user, usage_key): raise PermissionDenied() course_module = modulestore().get_course(usage_key, depth=3) # Lista dos Experimentos expList = ExperimentDefinition.objects.filter(userTeacher=request.user, course=course_module.location) lms_link = get_lms_link_for_item(course_module.location) # link para o LMS return render_to_response('experiment/experimentos.html', { 'lms_link': lms_link, 'explist': expList, 'course_key_string': course_key_string, 'context_course': course_module # Se não tiver essa variável não carregará o menu })
def test_rerun_course(self): """ Unit tests for :meth: `contentstore.tasks.rerun_course` """ mongo_course1_id = self.import_and_populate_course() # rerun from mongo into split split_course3_id = CourseLocator(org="edx3", course="split3", run="rerun_test") # Mark the action as initiated fields = {'display_name': 'rerun'} CourseRerunState.objects.initiated(mongo_course1_id, split_course3_id, self.user, fields['display_name']) result = rerun_course.delay(unicode(mongo_course1_id), unicode(split_course3_id), self.user.id, json.dumps(fields, cls=EdxJSONEncoder)) self.assertEqual(result.get(), "succeeded") self.assertTrue(has_course_access(self.user, split_course3_id), "Didn't grant access") rerun_state = CourseRerunState.objects.find_first( course_key=split_course3_id) self.assertEqual(rerun_state.state, CourseRerunUIStateManager.State.SUCCEEDED) # try creating rerunning again to same name and ensure it generates error result = rerun_course.delay(unicode(mongo_course1_id), unicode(split_course3_id), self.user.id) self.assertEqual(result.get(), "duplicate course") # the below will raise an exception if the record doesn't exist CourseRerunState.objects.find_first( course_key=split_course3_id, state=CourseRerunUIStateManager.State.FAILED) # try to hit the generic exception catch with patch( 'xmodule.modulestore.split_mongo.mongo_connection.MongoConnection.insert_course_index', Mock(side_effect=Exception)): split_course4_id = CourseLocator(org="edx3", course="split3", run="rerun_fail") fields = {'display_name': 'total failure'} CourseRerunState.objects.initiated(split_course3_id, split_course4_id, self.user, fields['display_name']) result = rerun_course.delay(unicode(split_course3_id), unicode(split_course4_id), self.user.id, json.dumps(fields, cls=EdxJSONEncoder)) self.assertIn("exception: ", result.get()) self.assertIsNone(self.store.get_course(split_course4_id), "Didn't delete course after error") CourseRerunState.objects.find_first( course_key=split_course4_id, state=CourseRerunUIStateManager.State.FAILED)
def create_item(parent_location, category, display_name, request, dt_metadata=None, datacomp=None): """ Cria um item no mongoDB de acordo com a categoria especificada. :param parent_location: onde sera criado o elemento :param category: categoria do experimento sequential, chapter e vertical :param display_name: nome que tera o componente criado :param dt_metadata: useless :param datacomp: useless :return: endereço do item criado """ parent = get_modulestore(category).get_item(parent_location) dest_location = parent_location.replace(category=category, name=uuid4().hex) if not has_course_access(request.user, parent_location): raise PermissionDenied() metadata = {} data = None if dt_metadata is not None: metadata = dt_metadata data = datacomp if display_name is not None: metadata['display_name'] = display_name get_modulestore(category).create_and_save_xmodule( dest_location, definition_data=data, metadata=metadata, system=parent.runtime, ) # # TODO replace w/ nicer accessor if not 'detached' in parent.runtime.load_block_type(category)._class_tags: parent.children.append(dest_location) # Vamos ver se fuciona get_modulestore(parent.location).update_item(parent, request.user.id) return dest_location
def test_rerun_course(self): """ Unit tests for :meth: `contentstore.tasks.rerun_course` """ mongo_course1_id = self.import_and_populate_course() # rerun from mongo into split split_course3_id = CourseLocator( org="edx3", course="split3", run="rerun_test" ) # Mark the action as initiated fields = {'display_name': 'rerun'} CourseRerunState.objects.initiated(mongo_course1_id, split_course3_id, self.user, fields['display_name']) result = rerun_course.delay(unicode(mongo_course1_id), unicode(split_course3_id), self.user.id, json.dumps(fields, cls=EdxJSONEncoder)) self.assertEqual(result.get(), "succeeded") self.assertTrue(has_course_access(self.user, split_course3_id), "Didn't grant access") rerun_state = CourseRerunState.objects.find_first(course_key=split_course3_id) self.assertEqual(rerun_state.state, CourseRerunUIStateManager.State.SUCCEEDED) # try creating rerunning again to same name and ensure it generates error result = rerun_course.delay(unicode(mongo_course1_id), unicode(split_course3_id), self.user.id) self.assertEqual(result.get(), "duplicate course") # the below will raise an exception if the record doesn't exist CourseRerunState.objects.find_first( course_key=split_course3_id, state=CourseRerunUIStateManager.State.FAILED ) # try to hit the generic exception catch with patch('xmodule.modulestore.split_mongo.mongo_connection.MongoConnection.insert_course_index', Mock(side_effect=Exception)): split_course4_id = CourseLocator(org="edx3", course="split3", run="rerun_fail") fields = {'display_name': 'total failure'} CourseRerunState.objects.initiated(split_course3_id, split_course4_id, self.user, fields['display_name']) result = rerun_course.delay(unicode(split_course3_id), unicode(split_course4_id), self.user.id, json.dumps(fields, cls=EdxJSONEncoder)) self.assertIn("exception: ", result.get()) self.assertIsNone(self.store.get_course(split_course4_id), "Didn't delete course after error") CourseRerunState.objects.find_first( course_key=split_course4_id, state=CourseRerunUIStateManager.State.FAILED )
def EmailsExp(request, course_key_string, idExp=None): """ Returns the list of email addresses for ARM {{define}}, which allows for the instructor to send messages to specific groups :param request: httprequest default :param idExp: experiment :return: CSV file format Retorna a lista de e-mails por ARM, o que pode permitir que o professor envie e-mails para um grupo em específico. :param request: httprequest default :param idExp: ID do experimento :return: CSV file format """ usage_key = CourseKey.from_string(course_key_string) if not has_course_access(request.user, usage_key): raise PermissionDenied() response = HttpResponse(content_type='text/csv; charset=utf-8') response['Content-Disposition'] = 'attachment; filename="relatorio2.csv"' writer = csv.writer(response) try: exp = ExperimentDefinition.objects.get(userTeacher=request.user, id=idExp) expsUsrsInfos={} uschs = UserChoiceExperiment.objects.filter(experimento=exp) print "Tamanho: ", len(uschs) # print "exp: ", exp listA = [] listB = [] listC = [] writer.writerow(['arm', 'usuario', 'e-mail']) for usch in uschs: if usch.versionExp.version == "A": listA.append(usch.userStudent) elif usch.versionExp.version == "B": listB.append(usch.userStudent) else: listC.append(usch.userStudent) for i in listA: writer.writerow(['A', i.username, i.email]) for i in listB: writer.writerow(['B', i.username, i.email]) for i in listC: writer.writerow(['C', i.username, i.email]) return response except: print "Erro ao pegar o exp"
def block_clone_handler(request, course_key_string): """ Permite clonar o conteúdo de uma dada semana do experimento. Além de clonar, nesta função faz a definição do experimento. o que insere entradas nas tabelas ExperimentDefinition, StrategyRandomization e OpcoesExperiment. :param request: http request com parent_location (location do curso) e mais source_locator (location da section) :param course_key_string: useless :return: json com OK """ letras = ['A', 'B', 'C', 'D'] if request.method in ('PUT', 'POST'): # Get location Course com base no valor passado pelo Json locatorCursokey = UsageKey.from_string(request.json['parent_locator']) locatorSectionKey = UsageKey.from_string(request.json['source_locator']) if not has_course_access(request.user, locatorSectionKey): raise PermissionDenied() # Verifica se já tem um experimento de acordo com o SourceLocation expSection = None try: opcExp = OpcoesExperiment.objects.get(sectionExp='%s' % request.json['source_locator']) temExp = True expSection = opcExp.experimento # pega o experimento para cadastrar a nova versao except: temExp = False # Pesquisa no banco de dados o Curso do qual duplicará os módulos course = modulestore().get_item(locatorCursokey, depth=3) sections = course.get_children() quantidade = 0 for section in sections: if locatorSectionKey == section.location: NewLocatorItemSection = create_item(locatorCursokey, 'chapter', section.display_name_with_default, request) # tem que Mudar para HomeWork, ou qualquer tipo que eu definir SectionLocation = NewLocatorItemSection descript = get_modulestore(NewLocatorItemSection).get_item(NewLocatorItemSection) storeSection = get_modulestore(NewLocatorItemSection) try: existing_item = storeSection.get_item(SectionLocation) field = existing_item.fields['start'] if section.start is not None: print "NÃO É NULO " field.write_to(existing_item, section.start) storeSection.update_item(existing_item, request.user.id) except: print "Start Date and end Date" subsections = section.get_children() quantidade = 0 if temExp: opcExp3 = OpcoesExperiment() opcExp3.experimento = expSection opcExp3.sectionExp = "%s" % NewLocatorItemSection opcExp3.sectionExp_url = '%s' % getURLSection(locatorCursokey, NewLocatorItemSection) lenOpcs = len(OpcoesExperiment.objects.filter(experimento=expSection)) opcExp3.version = letras[lenOpcs] opcExp3.save() st = opcExp3.experimento.strategy st.percents +=';0.0' st.save() else: st = StrategyRandomization() st.strategyType = 'UniformChoice' st.percents = '0.0;0.0' st.save() # Experiment defintion exp = ExperimentDefinition() exp.course = request.json['parent_locator'] exp.userTeacher = request.user now = datetime.datetime.now() exp.descricao='MyExperiment %s ' % now exp.strategy = st exp.save() # Define a primeira versão do experimento opcExp = OpcoesExperiment() opcExp.experimento = exp opcExp.sectionExp = "%s" % locatorSectionKey opcExp.sectionExp_url = "%s" % section.url_name opcExp.version = 'A' opcExp.save() # Define a segunda versão do experimento opcExp2 = OpcoesExperiment() opcExp2.experimento = exp opcExp2.sectionExp = "%s" % NewLocatorItemSection opcExp2.sectionExp_url = '%s' % getURLSection(locatorCursokey, NewLocatorItemSection) opcExp2.version = 'B' opcExp2.save() for subsection in subsections: print print print "Clonando SubSeção: ", subsection.location NewLocatorItemSubsection = create_item(NewLocatorItemSection, 'sequential', subsection.display_name_with_default, request) # Agora iremos testar os Units units_Subsection = subsection.get_children() print "Information about the subsection: " print "subsection.format: ", subsection.format print "subsection.start: ", subsection.start print "Subsection locator: ", NewLocatorItemSubsection # tem que Mudar para HomeWork, ou qualquer tipo que eu definir # subLocation = loc_mapper().translate_locator_to_location(NewLocatorItemSubsection) # print "vert Location: ", subLocation # old_location = course_location.replace(category='course_info', name=block) # # descript = get_modulestore(NewLocatorItemSubsection).get_item(NewLocatorItemSubsection) print "Descript: ", descript CourseGradingModel.update_section_grader_type(descript, subsection.format, request.user) # Start Value storeSection = get_modulestore(NewLocatorItemSubsection) try: existing_item = storeSection.get_item(NewLocatorItemSubsection) field = existing_item.fields['start'] if subsection.start is not None: print "NÃO É NULO " field.write_to(existing_item, subsection.start) storeSection.update_item(existing_item, request.user.id) except: print "Deu erro" # Print all Units for unit in units_Subsection: originalState = compute_publish_state(unit) destinationUnit = duplicate_item(NewLocatorItemSubsection, unit.location, unit.display_name_with_default, request.user) # Nesta parte faz-se a leitura se e privado ou publico, se publico, seta a variavel como publico try: print "Vou fazer o translation -- destinationUnit ", destinationUnit # unitLocation = loc_mapper().translate_locator_to_location(destinationUnit) unitLocation = destinationUnit print "unity location: ", unitLocation # Start Value storeUnit = get_modulestore(unitLocation) print "STORE UNIT" try: existing_itemUnit = storeUnit.get_item(unitLocation) except: print "Deu erro" print "Antes do public" if originalState == 'public': def _publish(block): # This is super gross, but prevents us from publishing something that # we shouldn't. Ideally, all modulestores would have a consistant # interface for publishing. However, as of now, only the DraftMongoModulestore # does, so we have to check for the attribute explicitly. store = get_modulestore(block.location) print "Peguei o Store" if hasattr(store, 'publish'): store.publish(block.location, request.user.id) _xmodule_recurse( existing_itemUnit, _publish ) except: print "Erro ao setar publico" dataR = {'ok': quantidade } # return JsonResponse(dataR)
def DefineStrategy(request, course_key_string, idExperiment=None): """ Allows for switching among PlanOut operators (UniformChoice and WeightedChoice) as well as specifying an experimental design created through JMP, R or Minitab :param request: http request default :param course_key_string: :param idExperiment: experiment id :return: render pages which allow for strategy definition Permite alternar entre os operadores do PlanOut (UniformChoice e WeightedChoice) e especificar um design do experimento criado pelo JMP, R ou Minitab. :param request: http request default :param course_key_string: :param idExperiment: id do experimento :return: renderiza a página que pemrite definir a estratégia """ mensagem = "" mensagemWeightedChoice = '' mensagemUniformChoice='' mensagemCustom='' mensagemCrossOver='' mensagemCluster='' usage_key = CourseKey.from_string(course_key_string) # print "Course Location: ", courseKey if not has_course_access(request.user, usage_key): raise PermissionDenied() csrf_token = csrf(request)['csrf_token'] exp = ExperimentDefinition.objects.get(pk=idExperiment) strategy = exp.strategy try: if request.POST: strategySel = request.POST['strategySel'] strategy.strategyType = strategySel if strategySel == 'WeightedChoice': # monta os percents fields = strategy.percents.split(';') cont = 0 maxl = len(fields) lista = [] for i in range(0, maxl): lista.append(str(request.POST['peso'+str(i)])) strategy.percents = ';'.join(lista) strategy.save() mensagemWeightedChoice = "WeightedChoice Salvo!" elif strategySel == 'planOut': # Este Design ainda não está funcionando apropriadamente strategy.planoutScript = request.POST['input'] strategy.planoutJson = request.POST['output'] strategy.save() mensagemCustom = 'PlanoutScript e Json salvos com sucesso!!' elif strategySel == 'UniformChoice': strategy.save() print "A estratégia é UniformChoice" mensagemUniformChoice = "UniformChoice Salvo!" elif strategySel == 'customdesign': strategy.customDesign = request.POST['customDesign'] strategy.save() elif strategySel == 'fatorial': strategy.fatorial = request.POST['fatorial'] strategy.save() elif strategySel == 'crossover': strategy.periodos = request.POST['periodos']+'' print 'ok here' try: ExpRel = request.POST['expRel'] print "ExpRel: ", ExpRel strategy.periodoRel = ExperimentDefinition.objects.get(pk=int(ExpRel)) except: print "Error!" strategy.periodoRel = exp print 'ok here2 ', strategy.periodoRel.id strategy.save() print "Design CrossOver saldo com sucesso" mensagemCrossOver='Design CrossOver salvo com sucesso!!!' elif strategySel == 'cluster': print "asdfasdf" quantGroups = request.POST['quantG'] quantCad = GroupsCluster.objects.filter(experiment=exp) # Para cada grupo cadastra-se ou atualiza -1 e o codigo para cadastrar for i in range(1, int(quantGroups)+1): seq = getSequencia(request, i) idG = request.POST[str(i)] if int(idG) == -1: g = GroupsCluster() g.experiment = exp strG = json.dumps(seq) g.grupos = strG g.save() else: g = GroupsCluster.objects.get(pk=int(idG)) strG = json.dumps(seq) g.grupos = strG g.save() toRemove = request.POST['RemoveIDS'] print "Toremove ", toRemove idsR = toRemove.split("|") for idr in idsR: try: if int(idr) != -1: print "Idr: ", idr g = GroupsCluster.objects.get(pk=int(idr)) g.delete() except: print 'Err rem', idr mensagemCluster='Design Cluster saved with success!!!' strategy.save() except: mensagem = 'Ocorreu um erro ao salvar a estratégia!!!' pesos = "<br />" arms = ['A', 'B', 'C', 'D', 'D', 'F'] # Render html pesos Weight cont = 0 # Pega a quantidade de versões #OpcoesExperiment.objects.filter(experimento=exp.) percents = strategy.percents.split(';') exps = ExperimentDefinition.objects.filter(course=exp.course) opcsSel = [] for expC in exps: if expC.strategy.strategyType == 'crossover': opcsSel.append(expC) for peso in percents: pesos += "Percent Arm "+arms[cont]+" <input type='text' name='peso"+str(cont)+"' class='form-control' value='"+str(peso)+"' /> <br />" cont += 1 linhas = [] try: #GruposJson = json.loads(exp.strategy.clusterGroups) clustersG = GroupsCluster.objects.filter(experiment=exp) print "Quant: ", len(clustersG) selectsgrupos = '' row = 1 for Line in clustersG: print "Cheguei aqui: " linha="<tr id='"+str(row)+"'>" SEQ = ['0', '3', '6', '9', '12'] cont = 0 try: line = json.loads(Line.grupos) print "line: ", line except: print "Other Group" continue for cond in line: if cont != 0: linha += '<td>and</td>' else: regId = "<input type='hidden' name='"+str(row)+"' id='f"+str(Line.id)+"' value='"+str(Line.id)+"' />" if cond['tipo'] == 'sexo': selectsgrupos += "$('#"+SEQ[cont]+"sexo"+str(row)+"').val('"+cond['val']+"'); " linha += "<td>"+regId+"Sexo: <input type='hidden' name='"+SEQ[cont]+"|"+str(row)+"' value='sexo' /></td>" linha += "<td><select id='"+SEQ[cont]+"sexo"+str(row)+"' name='"+SEQ[cont]+"|sexo|"+str(row)+"'><option value='m'>Masculino</option><option value='f'>Feminino</option></select> </td>" elif cond['tipo'] == 'escolaridade': selectsgrupos += "$('#"+SEQ[cont]+"escolaridade"+str(row)+"').val('"+cond['val']+"'); " linha += "<td>"+regId+"Escolaridade: <input type='hidden' name='"+SEQ[cont]+"|"+str(row)+"' value='escolaridade' /> </td>" linha += "<td><select id='"+SEQ[cont]+"escolaridade"+str(row)+"' name='"+SEQ[cont]+"|escolaridade|"+str(row)+"'><option value='p'> Doctorate </option> <option value='m'> Master's or professional degree</option><option value='b'> Bachelor's degree</option> <option value='a'> Associate's degree</option><option value='hs'> Secondary/high school</option> <option value='jhs'> Junior secondary/junior high/middle school</option><option value='el'>Elementary/primary school</option> <option value='none'>None</option> <option value='other'>Other</option> </td>" elif cond['tipo'] == 'pais': selectsgrupos += "$('#"+SEQ[cont]+"pais"+str(row)+"').val('"+cond['val']+"'); " from django_countries.countries import COUNTRIES options = '' for country in COUNTRIES: options += "<option value='"+country[0]+"'>"+country[1].encode('utf-8')+"</option>" linha += "<td>"+regId+"Pais: <input type='hidden' name='"+SEQ[cont]+"|"+str(row)+"' value='pais' /> </td>" linha += "<td><select id='"+SEQ[cont]+"pais"+str(row)+"' name='"+SEQ[cont]+"|pais|"+str(row)+"'> "+ options +"</select></td>" elif cond['tipo'] == 'age': selectsgrupos += "$('#"+SEQ[cont]+"condage"+str(row)+"').val('"+cond['c_age']+"'); " selectsgrupos += "$('#"+SEQ[cont]+"age"+str(row)+"').val('"+cond['val']+"');" linha += "<td>"+regId+"Age: <input type='hidden' name='"+SEQ[cont]+"|"+str(row)+"' value='age' /> </td>" linha += "<td><select id='"+SEQ[cont]+"condage"+str(row)+"' name='"+SEQ[cont]+"|condage|"+str(row)+"'> <option value='>'>></option><option value='<'><</option><option value='<='><=</option><option value='>='>>=</option></select> " linha += "<input id='"+SEQ[cont]+"age"+str(row)+"' name='"+SEQ[cont]+"|age|"+str(row)+"' type='number' min='0' max='100'/></td>" elif cond['tipo'] == 'city': selectsgrupos += "$('#"+SEQ[cont]+"city"+str(row)+"').val('"+cond['val']+"'); " linha += "<td>"+regId+"City like: <input type='hidden' name='"+SEQ[cont]+"|"+str(row)+"' value='city' /></td>" linha += "<td><input id='"+SEQ[cont]+"city"+str(row)+"' name='"+SEQ[cont]+"|city|"+str(row)+"' type='text'/></td>" cont += 1 if len(line) != 5: # tamanho maximo linha += '<td>and</td>' linha += "<td><input type='hidden' name='"+SEQ[cont]+"|"+str(row)+"' value='criteria' /> <select id='"+SEQ[cont]+"col"+str(row)+"'> <option value='gender'>Gender </option> <option value='age'>Age</option><option value='escolaridade'>Escolaridade</option><option value='country'>Country</option><option value='city'>City</option> </select> </td>" linha += "<td><input type='button' value='+' onclick='addFactor(this,"+SEQ[cont]+","+str(row)+");'/></td>" if len(line) == 1: linha += '<td></td>' linha += '<td></td>' linha += '<td></td>' linha += '<td></td>' linha += '<td></td>' linha += '<td></td>' linha += '<td></td>' linha += '<td></td>' linha += '<td></td>' elif len(line) == 2: linha += '<td></td>' linha += '<td></td>' linha += '<td></td>' linha += '<td></td>' linha += '<td></td>' linha += '<td></td>' elif len(line) == 3: linha += '<td></td>' linha += '<td></td>' linha += '<td></td>' linha += "<td><a onClick='upDateLen(this, "+str(Line.id)+");'><i class='fa fa-trash'></i></a></td> </tr>" row += 1 print "\nLinha: ", linha linhas.append(linha) except: import sys print "Unexpected error:", sys.exc_info() return render_to_response('experiment/estrategia.html', { 'course_key_string': course_key_string, 'csrf': csrf_token, 'idExperiment': idExperiment, 'strat': strategy, 'elementosStrat': '', 'pesos': pesos, 'mensagem': mensagem, 'mensagemWeightedChoice': mensagemWeightedChoice, 'mensagemUniformChoice': mensagemUniformChoice, 'mensagemCustom': mensagemCustom, 'mensagemCrossOver': mensagemCrossOver, 'mensagemCluster': mensagemCluster, 'exps': opcsSel, 'periodos': strategy.periodos, "expRel": (-1 if type(strategy.periodoRel) == type(None) else strategy.periodoRel.id), 'linhas': linhas, 'selectsgrupos': selectsgrupos, })
def test_get_all_users(self): """ Test getting all authors for a course where their permissions run the gamut of allowed group types. """ # first check the course creator.has explicit access (don't use has_access as is_staff # will trump the actual test) self.assertTrue( CourseInstructorRole(self.course_locator).has_user(self.user), "Didn't add creator as instructor." ) users = copy.copy(self.users) # doesn't use role.users_with_role b/c it's verifying the roles.py behavior user_by_role = {} # add the misc users to the course in different groups for role in [CourseInstructorRole, CourseStaffRole]: user_by_role[role] = [] # pylint: disable=protected-access groupnames = role(self.course_locator)._group_names self.assertGreater(len(groupnames), 1, "Only 0 or 1 groupname for {}".format(role.ROLE)) # NOTE: this loop breaks the roles.py abstraction by purposely assigning # users to one of each possible groupname in order to test that has_course_access # and remove_user work for groupname in groupnames: group, _ = Group.objects.get_or_create(name=groupname) user = users.pop() user_by_role[role].append(user) user.groups.add(group) user.save() self.assertTrue(has_course_access(user, self.course_locator), "{} does not have access".format(user)) self.assertTrue(has_course_access(user, self.course_location), "{} does not have access".format(user)) response = self.client.get_html(self.course_locator.url_reverse('course_team')) for role in [CourseInstructorRole, CourseStaffRole]: for user in user_by_role[role]: self.assertContains(response, user.email) # test copying course permissions copy_course_location = Location(['i4x', 'copyu', 'copydept.mycourse', 'course', 'myrun']) copy_course_locator = loc_mapper().translate_location( copy_course_location.course_id, copy_course_location, False, True ) for role in [CourseInstructorRole, CourseStaffRole]: auth.add_users( self.user, role(copy_course_locator), *role(self.course_locator).users_with_role() ) # verify access in copy course and verify that removal from source course w/ the various # groupnames works for role in [CourseInstructorRole, CourseStaffRole]: for user in user_by_role[role]: # forcefully decache the groups: premise is that any real request will not have # multiple objects repr the same user but this test somehow uses different instance # in above add_users call if hasattr(user, '_groups'): del user._groups self.assertTrue(has_course_access(user, copy_course_locator), "{} no copy access".format(user)) self.assertTrue(has_course_access(user, copy_course_location), "{} no copy access".format(user)) auth.remove_users(self.user, role(self.course_locator), user) self.assertFalse(has_course_access(user, self.course_locator), "{} remove didn't work".format(user))