def setUp(self): super(TestStateViewsFunctional, self).setUp() with transaction.manager: state = State(name="Sao Paolo") municipality1 = Municipality(name="Brasillia", parent=state) municipality2 = Municipality(name="Brasil", parent=state) user_group = Group(name="state_official") user = User() user.group = user_group user.location = state ona_user = OnaUser(username="******", user=user, refresh_token="1239khyackas") ona_user.save() reporting_period = ReportingPeriod( title='Period 1', start_date=datetime.datetime(2015, 5, 1), end_date=datetime.datetime(2015, 7, 31)) reporting_period.save() DBSession.add_all([state, municipality1, municipality2])
def test_add_clinics_to_user(self): self.setup_test_data() user = User() ona_user = OnaUser( user=user, username='******', refresh_token="c563e9") values = {'group': groups.CLINIC_MANAGER, 'clinics': ["1", "2", "3"]} ona_user.update(values) self.assertEqual(len(ona_user.user.clinics), 3)
def test_can_delete_ona_user(self): self._create_user("to_delete") ona_user_to_delete = OnaUser.get(OnaUser.username == 'to_delete') ona_user = OnaUser.get(OnaUser.username == 'manager_a') self.request.method = 'GET' self.request.user = ona_user.user self.request.context = ona_user_to_delete response = self.view.delete() self.assertEqual(response.status_code, 302) self.assertRaises( NoResultFound, OnaUser.get, OnaUser.user_id == ona_user_to_delete.user_id)
def test_update_new_user_group(self): user = User() ona_user = OnaUser( user=user, username='******', refresh_token="c563e9") self._create_municipality('Brazlandia') municipality = Municipality.get(Municipality.name == 'Brazlandia') values = {'group': groups.MUNICIPALITY_MANAGER, 'municipality': municipality.id} ona_user.update(values) self.assertEqual(ona_user.user.group.name, groups.MUNICIPALITY_MANAGER) self.assertEqual(ona_user.user.location, municipality)
def test_group_finder_returns_users_groups(self): self.setup_test_data() user = OnaUser.get(OnaUser.username == 'super').user request = testing.DummyRequest() groups = group_finder(user.id, request) self.assertListEqual(sorted(groups), sorted(['su', 'u:1']))
def test_get_clinics(self): self.setup_test_data() user = OnaUser.get(OnaUser.username == 'manager_a').user clinics = user.get_clinics() self.assertEqual(len(clinics), 1) self.assertEqual(clinics[0].name, "Clinic A")
def setUp(self): super(TestMunicipalityViews, self).setUp() self.request = testing.DummyRequest() self._create_user('municipality-manager') with transaction.manager: reporting_period = ReportingPeriod( title='Period 1', start_date=datetime.datetime(2015, 5, 1), end_date=datetime.datetime(2015, 7, 31)) reporting_period.save() municipality = Municipality(name="Brasillia") DBSession.add(municipality) for i in range(5): clinic = Clinic(name="Clinic {}".format(i), code="{}BCDE".format(i), municipality=municipality) DBSession.add(clinic) self.request.user = OnaUser.get( OnaUser.username == 'municipality-manager').user self.view = MunicipalityViews(self.request)
def setup_users(): group_criteria = Group.name == groups.SUPER_USER group_params = {'name': groups.SUPER_USER} su_group = Group.get_or_create( group_criteria, **group_params) su = User() user_profile_criteria = UserProfile.username == 'admin' user_profile_params = { 'user': su, 'username': '******', 'password': '******'} profile = UserProfile.get_or_create( user_profile_criteria, **user_profile_params) ona_user_params = { 'user': su, 'username': '******', 'refresh_token': '123456'} ona_user = OnaUser.get_or_create( OnaUser.username == "admin", **ona_user_params) su.group = su_group profile.save() ona_user.save()
def main(argv=sys.argv): if len(argv) != 5: usage(argv) config_uri = argv[1] setup_logging(config_uri) pwd_context.load_path(config_uri) settings = get_appsettings(config_uri) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.create_all(engine) username = argv[2] password = argv[3] group = argv[4] with transaction.manager: group_criteria = Group.name == group group_params = {'name': group} group = Group.get_or_create( group_criteria, **group_params) user = User() user.group = group profile = UserProfile( user=user, username=username, password=password) ona_user_params = { 'user': user, 'username': username, 'refresh_token': 'test'} ona_user = OnaUser.get_or_create( OnaUser.username == username, **ona_user_params) DBSession.add_all([user, profile, ona_user])
def setUp(self): super(TestStateViews, self).setUp() self.request = testing.DummyRequest() self._create_user('state-official') with transaction.manager: reporting_period = ReportingPeriod( title='Period 1', start_date=datetime.datetime(2015, 5, 1), end_date=datetime.datetime(2015, 7, 31)) reporting_period.save() state = State(name="Sao Paolo") municipality1 = Municipality(name="Brasillia", parent=state) municipality2 = Municipality(name="Brasil", parent=state) DBSession.add_all([state, municipality1, municipality2]) for i in range(5): clinic = Clinic(name="Clinic {}".format(i), code="{}BCDE".format(i), municipality=municipality1) DBSession.add(clinic) self.request.user = OnaUser.get( OnaUser.username == 'state-official').user self.view = StateViews(self.request)
def test_manager_can_list_clinics(self): ona_user = OnaUser.get(OnaUser.username == 'manager_a') self.config.testing_securitypolicy( userid=ona_user.user.id, permissive=True, groupids=(groups.MUNICIPALITY_MANAGER, )) has_permission = can_list_clinics(self.request) self.assertTrue(has_permission)
def test_assign_to_user(self): self.setup_test_data() user = OnaUser.get(OnaUser.username == 'manager_a').user clinic = Clinic.get(Clinic.name == "Clinic B") clinic.assign_to(user) user = DBSession.merge(user) clinic = DBSession.merge(clinic) self.assertEqual(clinic.user, user)
def test_get_or_create_from_api_data_returns_user_if_exists(self): user_data = { 'username': u"user_one", 'first_name': u"", 'last_name': u"" } # create the instance refresh_token = 'a123f4' OnaUser.get_or_create_from_api_data(user_data, refresh_token) # try to get or create new_refresh_token = 'b234f5' ona_user = OnaUser.get_or_create_from_api_data( user_data, new_refresh_token) self.assertIsInstance(ona_user, OnaUser) self.assertIsInstance(ona_user.user, User) self.assertEqual(ona_user.refresh_token, new_refresh_token)
def test_user_clinics_view_allows_none_role_user(self): self.setup_test_data() headers = self._login_user('none_role') # get the none role user user user = OnaUser.get(OnaUser.username == "none_role").user url = self.request.route_path( 'users', traverse=(user.id, 'clinics')) with HTTMock(get_edit_url_mock): response = self.testapp.get(url, headers=headers) self.assertEqual(response.status_code, 200)
def test_ona_user_logout(self): self.setup_test_data() ona_user = OnaUser.get(OnaUser.username == 'manager_a') request = testing.DummyRequest() request.context = ona_user.user request.user = ona_user.user response = logout(request) self.assertIsInstance(response, HTTPFound) self.assertEqual(response.location, request.route_url('auth', action='login'))
def test_manage_clinics_view(self): ona_user = OnaUser.get(OnaUser.username == 'manager_a') self.request.method = 'GET' self.request.user = ona_user.user user_clinics = ona_user.user.location.clinics response = self.clinic_views.manage_clinics() self.assertEqual(response['clinics'], user_clinics)
def test_oauth_authorize_accepted(self): state = 'a123f4' code = 'f27299' url = self.request.route_path('auth', action='callback') with HTTMock(oauth_token_mock, oauth_users_mock): response = self.testapp.get(url, params={ 'state': state, 'code': code }) # test that user is gotten or created OnaUser.get(OnaUser.username == 'user_one') self.assertEqual(response.status_code, 302) self.assertEqual(response.location, self.request.route_url('default')) # check that we set the login header self.assertIn('Set-Cookie', response.headers)
def oauth_callback(request): # check if we have `error` in our params, meaning user canceled if 'error' in request.GET: # redirect to login page with an alert request.session.flash(u"You must select authorize to continue", 'error') return HTTPFound(request.route_url('auth', action='login')) # TODO: validate the `oauth_state` session base_url = request.registry.settings['oauth_base_url'] state = request.GET.get('state') client_id = request.registry.settings['oauth_client_id'] client_secret = request.registry.settings['oauth_secret'] token_url = "{base_url}{path}".format( base_url=base_url, path=request.registry.settings['oauth_token_path']) redirect_uri = request.route_url('auth', action='callback') session = OAuth2Session(client_id, state=state, redirect_uri=redirect_uri) code = request.GET.get('code') token = session.fetch_token(token_url, client_secret=client_secret, code=code) # retrieve username and store in db if it doesnt exist yet user_api_url = "{base_url}{path}".format( base_url=base_url, path=request.registry.settings['oauth_user_api_path']) response = session.request('GET', user_api_url) try: user_data = json.loads(response.text) except ValueError: # couldn't decode json pass else: refresh_token = token['refresh_token'] try: ona_user = OnaUser.get_or_create_from_api_data( user_data, refresh_token) except ValueError: pass else: request.session['oauth_token'] = json.dumps(token) # flash to get the auto-inc id DBSession.flush() user_id = ona_user.user.id # login user headers = remember(request, user_id) # TODO: redirect to `came_from` url return HTTPFound(request.route_url('default'), headers=headers) request.session.flash(u"Failed to login, please try again", 'error') return HTTPFound(request.route_url('auth', action='login'))
def test_user_clinics_view(self): ona_user = OnaUser.get(OnaUser.username == 'manager_a') self.request.context = ona_user.user self.request.user = ona_user.user response = self.user_views.clinics() # we should only have Clinic A in the response self.assertIsInstance(response['period'], ReportingPeriod) self.assertEqual(len(response['locations']), 1) self.assertEqual(response['locations'][0].name, "Clinic A")
def test_delete_clinics(self): ona_user = OnaUser.get(OnaUser.username == 'manager_a') user_clinics = ona_user.user.get_clinics() clinic = user_clinics[0] self.request.method = 'GET' self.request.user = ona_user.user self.request.context = clinic response = self.clinic_views.delete() self.assertEqual(response.status_code, 302) self.assertRaises(NoResultFound, Clinic.get, Clinic.id == clinic.id)
def select_reporting_period(self): ona_user = OnaUser.get(OnaUser.username == 'manager_a') request = testing.DummyRequest() request.context = ona_user.user request.user = ona_user.user user_views = UserViews(request) with HTTMock(get_edit_url_mock): response = user_views.select_reporting_period() self.assertGreater(len(response['periods']), 0) self.assertEquals(response['user'], ona_user.user)
def test_get_or_create_from_api_data_creates_user(self): user_data = { 'username': u"user_one", 'first_name': u"", 'last_name': u"" } refresh_token = 'a123f4' ona_user = OnaUser.get_or_create_from_api_data( user_data, refresh_token) self.assertIsInstance(ona_user, OnaUser) self.assertIsInstance(ona_user.user, User)
def test_update_user_to_state_official(self): self.setup_test_data() self._create_state('Acre') state = State.get(Municipality.name == 'Acre') values = {'group': groups.STATE_OFFICIAL, 'state': state.id} manager = OnaUser.get(OnaUser.username == 'manager_a') manager.update(values) self.assertEqual(manager.user.location, state)
def test_update_ona_user_location(self): self.setup_test_data() self._create_municipality('Brazlandia') municipality = Municipality.get(Municipality.name == 'Brazlandia') values = {'group': groups.MUNICIPALITY_MANAGER, 'municipality': municipality.id} manager = OnaUser.get(OnaUser.username == 'manager_a') manager.update(values) self.assertEqual(manager.user.location, municipality)
def test_only_super_user_can_change_user_roles(self): ona_user = OnaUser.get(OnaUser.username == 'manager_a') url = self.request.route_url( 'admin', traverse=(ona_user.user.id, 'edit')) headers = self._login_user('manager_b') response = self.testapp.get(url, headers=headers, status=403) # Clinic Manager cannot access Admin pages self.assertEqual(response.status_code, 403) # Super User can access admin view headers = self._login_user('super') response = self.testapp.get(url, headers=headers) self.assertEqual(response.status_code, 200)
def test_can_delete_dashboard_user(self): self._create_dash_user('dash_user', '1234', '*****@*****.**') dashboard_user = UserProfile.get(UserProfile.username == 'dash_user') ona_user = OnaUser.get(OnaUser.username == 'manager_a') self.request.method = 'GET' self.request.user = ona_user.user self.request.context = dashboard_user response = self.view.delete() self.assertEqual(response.status_code, 302) self.assertRaises( NoResultFound, UserProfile.get, OnaUser.user_id == dashboard_user.user_id)
def test_can_edit_user_groups(self): ona_user = OnaUser.get(OnaUser.username == 'manager_a') user = ona_user.user self.request.context = user self.request.method = 'POST' params = MultiDict({'group': groups.CLINIC_MANAGER, 'clinics': ['1'], 'municipality': '1', 'state': '2'}) self.request.POST = params response = self.view.edit() self.assertEqual(response.status_code, 302) self.assertEqual(ona_user.user.group.name, groups.CLINIC_MANAGER)
def test_register_clinic_doesnt_save_clinics_with_same_codes(self): ona_user = OnaUser.get(OnaUser.username == 'manager_a') municipality = Municipality.get(Municipality.name == "Brazilia") clinic = Clinic.get(Clinic.code == '1A2B') params = MultiDict({ 'municipality': "{}".format(municipality.id), 'name': "New Clinic Name", 'code': clinic.code }) self.request.method = 'POST' self.request.ona_user = ona_user self.request.POST = params self.clinic_views.register_clinic() flash_error = self.request.session.pop_flash('error')[0] self.assertTrue(flash_error.find("exists") != -1)
def test_can_register_new_clinic_users(self): ona_user = OnaUser.get(OnaUser.username == 'manager_a') user = ona_user.user old_user_count = User.count() self.request.context = user self.request.method = 'POST' params = MultiDict({'email': "*****@*****.**", 'username': "******", 'password': {'password': '******', 'password-confirm': 'password'}, 'group': groups.CLINIC_MANAGER, 'clinics': ['1']}) self.request.POST = params response = self.view.register() self.assertEqual(User.count(), old_user_count + 1) self.assertEqual(response.status_code, 302)
def test_can_register_new_state_users(self): self._create_state() ona_user = OnaUser.get(OnaUser.username == 'manager_a') user = ona_user.user old_user_count = User.count() state = State.newest() self.request.context = user self.request.method = 'POST' params = MultiDict({'email': "*****@*****.**", 'username': "******", 'password': {'password': '******', 'password-confirm': 'password'}, 'group': groups.STATE_OFFICIAL, 'state': "{}".format(state.id)}) self.request.POST = params response = self.view.register() self.assertEqual(User.count(), old_user_count + 1) self.assertEqual(response.status_code, 302)