def setUp(self): """Set testing environment.""" biz_orgs_list = ['BIZ_org_1'] npf_orgs_list = ['NPF_org_1', 'NPF_org_2', 'openCurrents'] volunteers_list = ['volunteer_1'] test_setup = SetUpTests() test_setup.generic_setup(npf_orgs_list, biz_orgs_list, volunteers_list) # setting orgs self.org_npf = test_setup.get_all_npf_orgs()[0] self.org_npf2 = test_setup.get_all_npf_orgs()[1] self.org_biz = test_setup.get_all_biz_orgs()[0] # set up project self.project = test_setup.get_all_projects(self.org_npf)[0] self.project2 = test_setup.get_all_projects(self.org_npf2)[0] # creating BIZ admin all_admins = test_setup.get_all_biz_admins() self.biz_admin = all_admins[0] # creating npf admins all_admins = test_setup.get_all_npf_admins() self.npf_admin = all_admins[0] self.npf_admin2 = all_admins[1] self.org_admin = OrgAdmin(self.npf_admin.id) # assigning existing volunteers to variables all_volunteers = test_setup.get_all_volunteers() self.volunteer_1 = all_volunteers[0] # oc instances self.oc_npf_adm = OcUser(self.npf_admin.id) # self.org_biz_adm = BizAdmin(self.biz_admin.id) self.oc_vol_1 = OcUser(self.volunteer_1.id) # user entities self.vol_1_entity = UserEntity.objects.get(user=self.volunteer_1) self.user_enitity_id_vol_1 = UserEntity.objects.get( user=self.volunteer_1).id # creating an offer self.offer = _create_offer( self.org_biz, currents_share=_SHARE * 100) # create master offer # _create_offer( # Org.objects.get(name='openCurrents'), # currents_share=100, # is_master=1 # ) # getting item self.purchased_item = Item.objects.filter(offer__id=self.offer.id)[0] # setting up client self.client = Client() self.client.login(username=self.npf_admin.username, password='******')
def test_update_names(self): ''' tests first or last name are updated ''' user = OcUser(self.userReg.id) user.update_user(first_name='Jay') first_name = user.get_user().first_name self.assertEqual(first_name, 'Jay')
def setUp(self): """Set testing environment.""" self.url_signup = reverse('process_signup', urlconf=urls, kwargs={'mock_emails': 1}) self.url_login = reverse('process_login', urlconf=urls) biz_orgs_list = ['BIZ_org_1'] npf_orgs_list = ['NPF_org_1'] volunteers_list = ['volunteer_1'] test_setup = SetUpTests() test_setup.generic_setup(npf_orgs_list, biz_orgs_list, volunteers_list) # setting orgs self.org_npf = test_setup.get_all_npf_orgs()[0] # set up project self.project = test_setup.get_all_projects(self.org_npf)[0] self.project_id = self.project.id # creating an npf admin all_admins = test_setup.get_all_npf_admins() self.npf_admin = all_admins[0] self.org_admin = OrgAdmin(self.npf_admin.id) # assigning existing volunteers to variables all_volunteers = test_setup.get_all_volunteers() self.volunteer_1 = all_volunteers[0] # oc instances self.oc_npf_adm = OcUser(self.npf_admin.id) # self.org_biz_adm = BizAdmin(self.biz_admin.id) self.oc_vol_1 = OcUser(self.volunteer_1.id) # user entities self.vol_1_entity = UserEntity.objects.get(user=self.volunteer_1) self.user_enitity_id_vol_1 = UserEntity.objects.get( user=self.volunteer_1).id # dates and event future_date = timezone.now() + timedelta(days=1) self.event1 = _create_event(self.project, self.npf_admin.id, future_date, future_date + timedelta(hours=5), is_public=True) # setting up client self.client = Client()
def setup_redemptions(users, orgs): biz_orgs = [org for org in orgs if org.status == 'biz'] transactions = Transaction.objects.filter(user__in=users) if len(transactions) >= 20: print 'Sufficient number of redemptions already' return for i in xrange(20): org = _get_random_item(biz_orgs) orgs_offers = Offer.objects.filter(org=org) users = [ user for user in users if OcUser(user.id).get_balance_available() > 0 ] if not users: print 'No users with currents available!' return user = _get_random_item(users) user_balance = OcUser(user.id).get_balance_available() amount_spent_cur = round(random.random() * float(user_balance), 3) offer = _get_random_item(orgs_offers) price_reported = round(1000. / offer.currents_share * amount_spent_cur, 2) transaction = Transaction.objects.create( user=user, offer=offer, pop_no_proof=_get_random_string(), pop_type='oth', price_reported=price_reported, currents_amount=amount_spent_cur) action = random.choice(['req', 'app', 'red', 'dec']) transaction_action = TransactionAction.objects.create( transaction=transaction, action_type=action) print str(transaction_action) is_verified = (action in ['app', 'red']) if is_verified: OcLedger().transact_currents(entity_type_from='user', entity_id_from=user.userentity.id, entity_type_to='org', entity_id_to=org.orgentity.id, action=transaction_action, amount=amount_spent_cur)
def clean(self): cleaned_data = super(RedeemCurrentsForm, self).clean() redeem_receipt = cleaned_data['redeem_receipt'] redeem_no_proof = cleaned_data['redeem_no_proof'] redeem_price = cleaned_data['redeem_price'] user_balance_available = OcUser(self.user.id).get_balance_available() if user_balance_available <= 0: raise ValidationError( _('You don\'t have any currents to spend at this time')) if redeem_price <= 0: raise ValidationError(_('Invalid purchase price reported')) if redeem_receipt: content_type = redeem_receipt.content_type.split('/')[0] if content_type in settings.CONTENT_TYPES: if redeem_receipt._size > settings.MAX_UPLOAD_SIZE: raise ValidationError( _('Please keep image size under {}. Current size {}'). format(filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(redeem_receipt._size))) else: raise ValidationError(_('File type is not supported')) # comment out if no requirements for receipts or desc. elif not redeem_no_proof: raise ValidationError( _('Receipt or description of purchase is required')) return cleaned_data
def __init__(self, userid): self.userid = userid # org self.org = OcUser(self.userid).get_org() if not self.org or self.org.status != 'biz': raise InvalidAffiliation
def create_user(org_user_name, org, is_org_user=False, is_org_admin=False, password='******'): """ Crete Users and maps them to the org if needed. org_user_name - string if is_org_user = True, the user will be mapped to the org if is_org_admin = True, the user will be made an org admin org - Org object """ org_user = OcUser().setup_user(username=org_user_name, email=org_user_name + '@email.cc', first_name=org_user_name + '_first_name', last_name=org_user_name + '_last_name') if is_org_user: # mapping user to org oui = OrgUserInfo(org_user.id) oui.setup_orguser(org) # making a user an org admin if is_org_admin: oui.make_org_admin(org.id) org_user.set_password(password) org_user.save()
def setUp(self): ''' set up test fixtures ''' self.ledger = OcLedger() # set up regular user self.userReg = OcUser().setup_user( username='******', email='*****@*****.**', ) # set up user with a npf affiliation self.userOrg = OcUser().setup_user( username='******', email='*****@*****.**', ) # set up user with a biz affiliation self.userBiz = OcUser().setup_user( username='******', email='*****@*****.**', ) # set up test org self.orgTest = OcOrg().setup_org(name='test_org_123', status='npf') self.projectUserRegMT = Project(org=self.orgTest, name='MT by userReg') self.projectUserRegMT.save() self.eventUserRegMT = Event( project=self.projectUserRegMT, description='MT by userReg', location='test', coordinator=self.userOrg, creator_id=self.userOrg.id, event_type='MN', datetime_start=datetime.now(tz=pytz.utc) - timedelta(hours=2), datetime_end=datetime.now(tz=pytz.utc) - timedelta(hours=1)) self.eventUserRegMT.save() self.userRegTimeLog = UserTimeLog( user=self.userReg, event=self.eventUserRegMT, is_verified=True, datetime_start=datetime.now(tz=pytz.utc), datetime_end=datetime.now(tz=pytz.utc) + timedelta(hours=1)) self.userRegTimeLog.save() self.actionUserReg = AdminActionUserTime( user=self.userOrg, usertimelog=self.userRegTimeLog, action_type='app') self.actionUserReg.save() # issue currents to userReg self.ledger.issue_currents(self.orgTest.orgentity.id, self.userReg.userentity.id, self.actionUserReg, 1)
def assert_redeemed_amount_usd( self, user, sum_payed, share=_SHARE, # default biz org share tr_fee=_TR_FEE, # transaction fee currently 15% usdcur=_USDCUR # exchange rate usd per 1 curr ): """Assert the amount of pending dollars after a transaction.""" accepted_sum = sum_payed * share expected_usd = accepted_sum - accepted_sum * tr_fee usd_pending = OcUser(user.id).get_balance_pending_usd() self.assertEqual(usd_pending, expected_usd)
def setup_users(): users_all = [] for fxt in fixtures_user: try: user = OcUser().setup_user(fxt['email'], fxt['email'], fxt['firstname'], fxt['lastname']) print 'Created user %s' % user.username except UserExistsException: user = User.objects.get(email=fxt['email']) print 'User %s already exists' % fxt['email'] user.set_password('oc') user.save() users_all.append(user) if fxt['type'] != 'volunteer': org = None orgname = fxt['lastname'].strip('Admin') try: org = Org.objects.get(name=orgname) except Exception as e: print 'No org named %s (%s)' % (orgname, org.name) return oui = OrgUserInfo(user.id) try: oui.setup_orguser(org) except InvalidOrgUserException: print 'Unable to configure %s <=> %s mapping (possible it already exists)' % ( org.name, fxt['email']) try: oui.make_org_admin(org.id) except InvalidOrgException: print 'Unable to grant admin privilege to %s on org %s (check for exitence of admin group)' % ( user.username, org.name) except ExistingAdminException: print '%s already granted admin privilege on org %s' % ( user.username, org.name) return users_all
def setUp(self): """Set up test fixtures.""" _TEST_UUID = uuid.uuid4() self.client = Client() # set up regular user userRegEmail = '*****@*****.**' % _TEST_UUID self.userReg = OcUser().setup_user( username=userRegEmail, email=userRegEmail, ) # set up user with a npf affiliation userOrgEmail = '*****@*****.**' % _TEST_UUID self.userOrg = OcUser().setup_user( username=userOrgEmail, email=userOrgEmail, ) # set up user with a biz affiliation userBizEmail = '*****@*****.**' % _TEST_UUID self.userBiz = OcUser().setup_user( username=userBizEmail, email=userBizEmail, ) # set up test org self.orgTest = OcOrg().setup_org( name='test_org_existing', status='npf' ) # link org user to test org OrgUserInfo(self.userOrg.id).setup_orguser(self.orgTest) # user email used in tests self.test_email = '*****@*****.**' % _TEST_UUID Token.objects.filter(email=self.test_email).delete() # org users in tests self.test_org_name = 'test_org_%s' % _TEST_UUID
def _create_test_user( user_name, password='******', org=None, is_org_admin=False ): """ Create users and maps them to the org if needed. Takes: user_name - string org - Org object. A NPF admin will be created, if Org is provided and is_org_admin = True. An org user will be created if org is provided and is_org_admin = False. If no org provided - a volunteer will be created. is_org_admin - if True, the user will be made an org admin, if org is provided. """ test_user = OcUser().setup_user( username=user_name, email=user_name + '@email.cc', first_name=user_name + '_first_name', last_name=user_name + '_last_name' ) if org: # mapping user to org oui = OrgUserInfo(test_user.id) oui.setup_orguser(org) # making a user an org admin if is_org_admin: oui.make_org_admin(org.id) test_user.set_password(password) test_user.save() return test_user
def setUp(self): ''' set up test fixtures ''' # set up regular user self.userReg = OcUser().setup_user( username='******', email='*****@*****.**', ) # set up user with a npf affiliation self.userOrg = OcUser().setup_user( username='******', email='*****@*****.**', ) # set up user with a biz affiliation self.userBiz = OcUser().setup_user( username='******', email='*****@*****.**', ) # set up test org self.orgTest = OcOrg().setup_org(name='test_org_123', status='npf')
def test_user_exists(self): ''' tests user was created ''' user = OcUser(self.userReg.id).get_user() self.assertIsNotNone(user)
class TestOcUser(TestCase): def setUp(self): ''' set up test fixtures ''' # set up regular user self.userReg = OcUser().setup_user( username='******', email='*****@*****.**', ) # set up user with a npf affiliation self.userOrg = OcUser().setup_user( username='******', email='*****@*****.**', ) # set up user with a biz affiliation self.userBiz = OcUser().setup_user( username='******', email='*****@*****.**', ) # set up test org self.orgTest = OcOrg().setup_org(name='test_org_123', status='npf') def tearDown(self): ''' clean up test fixtures ''' self.userReg.delete() self.userOrg.delete() self.userBiz.delete() self.orgTest.delete() def test_user_exists(self): ''' tests user was created ''' user = OcUser(self.userReg.id).get_user() self.assertIsNotNone(user) def test_user_entity_exists(self): ''' tests user entity was created ''' user = OcUser(self.userReg.id) self.assertIsNotNone(user.get_user_entity()) def test_update_names(self): ''' tests first or last name are updated ''' user = OcUser(self.userReg.id) user.update_user(first_name='Jay') first_name = user.get_user().first_name self.assertEqual(first_name, 'Jay') def test_invalid_user(self): ''' check appropriate exception raised when invalid user requested ''' def _invalid_user(): user = OcUser(-1) self.assertRaises(InvalidUserException, _invalid_user) def test_user_exists(self): '''
class TestSignup(TransactionTestCase): """Main test class.""" def setUp(self): """Set up test fixtures.""" _TEST_UUID = uuid.uuid4() self.client = Client() # set up regular user userRegEmail = '*****@*****.**' % _TEST_UUID self.userReg = OcUser().setup_user( username=userRegEmail, email=userRegEmail, ) # set up user with a npf affiliation userOrgEmail = '*****@*****.**' % _TEST_UUID self.userOrg = OcUser().setup_user( username=userOrgEmail, email=userOrgEmail, ) # set up user with a biz affiliation userBizEmail = '*****@*****.**' % _TEST_UUID self.userBiz = OcUser().setup_user( username=userBizEmail, email=userBizEmail, ) # set up test org self.orgTest = OcOrg().setup_org( name='test_org_existing', status='npf' ) # link org user to test org OrgUserInfo(self.userOrg.id).setup_orguser(self.orgTest) # user email used in tests self.test_email = '*****@*****.**' % _TEST_UUID Token.objects.filter(email=self.test_email).delete() # org users in tests self.test_org_name = 'test_org_%s' % _TEST_UUID def tearDown(self): """Clear up test fixtures.""" self.userReg.delete() self.userOrg.delete() self.userBiz.delete() self.orgTest.delete() User.objects.filter(username=self.test_email).delete() Token.objects.filter(email=self.test_email).delete() org = None try: org = Org.objects.get(name=self.test_org_name) except Exception: pass # delete org admin group if org: Group.objects.filter(name='admin_%s' % org.name).delete() Org.objects.filter(name=self.test_org_name).delete() def _assert_user(self, username, is_true): ''' assert user exists ''' users = User.objects.filter(username=username) does_exist = users.exists() if is_true: self.assertTrue(does_exist) return users[0] else: self.assertFalse(does_exist) return None def _assert_user_has_usable_password(self, username, is_true): ''' assert user exists and has a password set ''' try: user = User.objects.get(username=username) except User.DoesNotExist: self.assertFalse(is_true) has_usable_password = user.has_usable_password() if is_true: self.assertTrue(has_usable_password) else: self.assertFalse(has_usable_password) def _assert_num_users(self, user_email, num_users): ''' assert number of user for a given email ''' users = User.objects.filter(email=user_email) self.assertEqual(len(users), num_users) def _assert_token_valid(self, username, is_true): ''' assert valid verification token was generated - unverified - type signup - timestamp recent enough ''' nowish = datetime.now(tz=pytz.utc) - timedelta(seconds=3) tokens = Token.objects.filter( email=username, is_verified=False, token_type='signup', date_created__gte=nowish, date_expires__gte=nowish + timedelta(days=6), date_expires__lte=nowish + timedelta(days=8) ) if is_true: self.assertTrue(tokens.exists()) else: self.assertFalse(tokens.exists()) def _assert_org(self, org_name, org_status, is_true): ''' assert org exists and is unique ''' orgs = Org.objects.filter(name=org_name) if is_true: self.assertTrue(orgs.exists()) self.assertEqual(len(orgs), 1) self.assertEqual(orgs[0].status, org_status) return orgs[0] else: self.assertFalse(orgs.exists()) def _assert_org_user(self, org_name, user_email, is_true): ''' assert orguser association exists and is unique ''' orgusers = OrgUser.objects.filter( org__name=org_name, user__email=user_email ) if is_true: self.assertTrue(orgusers.exists()) self.assertEqual(len(orgusers), 1) else: self.assertFalse(orgusers.exists()) def _assert_group(self, org_name, is_true): ''' assert empty user group exists and is unique ''' org = None try: org = Org.objects.get(name=org_name) except Exception as e: pass if is_true: self.assertTrue(org) else: self.assertFalse(org) groups = Group.objects.filter(name='admin_%s' % org.id) if is_true: self.assertTrue(groups.exists()) self.assertEqual(len(groups), 1) if org.status == 'biz': self.assertEqual(len(groups[0].user_set.all()), 1) else: self.assertFalse(groups[0].user_set.all()) return groups[0] else: self.assertFalse(groups.exists()) def test_signup_user_new(self): ''' test signup successful for a new user - user should be created - user should have no password set - token should have been generated - redirected to 'check-email' ''' self._assert_user(self.test_email, False) self._assert_token_valid(self.test_email, False) response = self.client.post( testing_urls.url_signup, data={ 'user_email': self.test_email, 'user_firstname': 'test_firstname', 'user_lastname': 'test_lastname', 'signup_status': 'vol' } ) self._assert_user(self.test_email, True) self._assert_user_has_usable_password(self.test_email, False) self._assert_token_valid(self.test_email, True) url_check_email = reverse( 'check-email', urlconf=urls, kwargs={'user_email': self.test_email} ) self.assertRedirects(response, url_check_email) def test_signup_user_existing_no_password(self): ''' tests signup successful for existing user without password - new user not created - existing user should be used - user should have no password set - token should have been generated - redirected to 'check-email' ''' self._assert_user(self.userReg.username, True) self._assert_num_users(self.userReg.email, 1) self._assert_user_has_usable_password(self.userReg.username, False) response = self.client.post( testing_urls.url_signup, data={ 'user_email': self.userReg.email, 'user_firstname': 'test_firstname', 'user_lastname': 'test_lastname', 'signup_status': 'vol' } ) user = self._assert_user(self.userReg.email, True) self._assert_num_users(self.userReg.email, 1) self._assert_user_has_usable_password(self.userReg.email, False) self._assert_token_valid(self.userReg.email, True) # check first and last name were updated self.assertEqual(user.first_name, 'test_firstname') self.assertEqual(user.last_name, 'test_lastname') url_check_email = reverse( 'check-email', urlconf=urls, kwargs={'user_email': self.userReg.email} ) self.assertRedirects(response, url_check_email) def test_signup_user_existing_with_password(self): ''' tests signup successful for existing user with password - new user not created - existing user should be used - token not generated - redirected to 'login' ''' self._assert_user(self.userReg.username, True) self._assert_user_has_usable_password(self.userReg.username, False) self._assert_num_users(self.userReg.email, 1) self._assert_token_valid(self.userReg.email, False) # set password for user self.userReg.set_password(uuid.uuid4()) self.userReg.save() self._assert_user_has_usable_password(self.userReg.username, True) response = self.client.post( testing_urls.url_signup, data={ 'user_email': self.userReg.email, 'user_firstname': 'test_firstname', 'user_lastname': 'test_lastname', 'signup_status': 'vol' } ) self._assert_num_users(self.userReg.email, 1) self._assert_token_valid(self.userReg.email, False) url_login = reverse( 'login', urlconf=urls, kwargs={ 'status_msg': 'User with this email already exists', 'msg_type': 'alert' } ) self.assertRedirects(response, url_login) def test_signup_user_org_npf_new(self): ''' tests signup successful for new org user - new user created - token generated - org created - org user created - org admin group created - redirected to 'check-email' with org id ''' self._assert_user(self.test_email, False) response = self.client.post( testing_urls.url_signup, data={ 'user_email': self.test_email, 'user_firstname': 'test_firstname', 'user_lastname': 'test_lastname', 'npf_name': self.test_org_name, 'signup_status': 'npf' } ) self._assert_user(self.test_email, True) self._assert_user_has_usable_password(self.test_email, False) self._assert_token_valid(self.test_email, True) org = self._assert_org(self.test_org_name, 'npf', True) self._assert_org_user(self.test_org_name, self.test_email, True) self._assert_group(self.test_org_name, True) url_login = reverse( 'check-email', urlconf=urls, kwargs={ 'user_email': self.test_email, 'orgid': org.id } ) self.assertRedirects(response, url_login) def test_signup_user_org_biz_new(self): ''' tests signup successful for new biz user - new user created - token generated - biz org created - biz org user created - biz admin group created - redirected to 'check-email' with org id ''' self._assert_user(self.test_email, False) response = self.client.post( testing_urls.url_signup, data={ 'user_email': self.test_email, 'user_firstname': 'test_firstname', 'user_lastname': 'test_lastname', 'biz_name': self.test_org_name, 'signup_status': 'biz' } ) self._assert_user(self.test_email, True) self._assert_user_has_usable_password(self.test_email, False) self._assert_token_valid(self.test_email, True) org = self._assert_org(self.test_org_name, 'biz', True) self._assert_org_user(self.test_org_name, self.test_email, True) self._assert_group(self.test_org_name, True) # url_login = reverse( # 'check-email', # urlconf=urls, # kwargs={ # 'user_email': self.test_email, # 'orgid': org.id # } # ) url_redirect = reverse( 'offer', urlconf=urls, ) self.assertRedirects(response, url_redirect) @skip('Fix (#1567)') def test_signup_user_org_existing(self): ''' tests signup fails for invalid org - new user created - token generated - biz org not created - biz org user not created - biz admin group not created - redirected to 'nonprofit' with proper status message ''' self._assert_user(self.test_email, False) self._assert_org(self.orgTest.name, 'npf', True) response = self.client.post( testing_urls.url_signup, data={ 'user_email': self.test_email, 'user_firstname': 'test_firstname', 'user_lastname': 'test_lastname', 'npf_name': self.orgTest.name, 'signup_status': 'npf' } ) self._assert_user(self.test_email, False) # we don't create a user if org exists self._assert_token_valid(self.test_email, False) self._assert_org_user(self.orgTest.name, self.test_email, False) status_message = 'Organization named %s already exists!' % self.orgTest.name warning_messages = list(response.wsgi_request._messages) self.assertEqual(warning_messages[0].message, status_message) self.assertIn('alert', warning_messages[0].tags) url_nonprofit = reverse( 'home', urlconf=urls, ) + '#signup' self.assertRedirects(response, url_nonprofit) def test_signup_livedashboard_optin(self): ''' test signup from live dashboard with optin - user created - user no password set - token not generated - response status code 201 with user id ''' self._assert_user(self.test_email, False) self._assert_token_valid(self.test_email, False) response = self.client.post( testing_urls.url_signup_endpoint, data={ 'user_email': self.test_email, 'user_firstname': 'test_firstname', 'user_lastname': 'test_lastname', 'org_admin_id': self.userOrg.id, 'signup_status': 'vol' } ) user = self._assert_user(self.test_email, True) self._assert_user_has_usable_password(self.test_email, False) self._assert_token_valid(self.test_email, False) self.assertEqual(int(response.status_code), 201) self.assertEqual(int(response.content), user.id)
def _invalid_user(): user = OcUser(-1)
from django.contrib.auth.models import User from csv import writer from datetime import datetime, timedelta from pytz import utc users = User.objects.filter(is_staff=False) data = {} for user in users: try: us = user.usersettings except UserSettings.DoesNotExist: continue ocuser = OcUser(user.id) print user.id hours_req = ocuser.get_hours_requested() for req in hours_req: admin_user = req.user orguserinfo = OrgUserInfo(admin_user.id) is_approved = False try: is_approved = orguserinfo.is_org_admin() except: pass is_approved_with_org = orguserinfo.is_org_admin( req.usertimelog.event.project.org.id) data[req.id] = {
class TestOcLedger(TestCase): def setUp(self): ''' set up test fixtures ''' self.ledger = OcLedger() # set up regular user self.userReg = OcUser().setup_user( username='******', email='*****@*****.**', ) # set up user with a npf affiliation self.userOrg = OcUser().setup_user( username='******', email='*****@*****.**', ) # set up user with a biz affiliation self.userBiz = OcUser().setup_user( username='******', email='*****@*****.**', ) # set up test org self.orgTest = OcOrg().setup_org(name='test_org_123', status='npf') self.projectUserRegMT = Project(org=self.orgTest, name='MT by userReg') self.projectUserRegMT.save() self.eventUserRegMT = Event( project=self.projectUserRegMT, description='MT by userReg', location='test', coordinator=self.userOrg, creator_id=self.userOrg.id, event_type='MN', datetime_start=datetime.now(tz=pytz.utc) - timedelta(hours=2), datetime_end=datetime.now(tz=pytz.utc) - timedelta(hours=1)) self.eventUserRegMT.save() self.userRegTimeLog = UserTimeLog( user=self.userReg, event=self.eventUserRegMT, is_verified=True, datetime_start=datetime.now(tz=pytz.utc), datetime_end=datetime.now(tz=pytz.utc) + timedelta(hours=1)) self.userRegTimeLog.save() self.actionUserReg = AdminActionUserTime( user=self.userOrg, usertimelog=self.userRegTimeLog, action_type='app') self.actionUserReg.save() # issue currents to userReg self.ledger.issue_currents(self.orgTest.orgentity.id, self.userReg.userentity.id, self.actionUserReg, 1) def tearDown(self): ''' clean up test fixtures ''' self.userReg.delete() self.userOrg.delete() self.userBiz.delete() self.orgTest.delete() Ledger.objects.filter(entity_from__id__in=[ self.userReg.userentity.id, self.userOrg.userentity.id, self.userBiz.userentity.id, self.orgTest.orgentity.id ]).delete() def test_initial_balance(self): ''' test initial balances correct after set up ''' self.assertEqual(self.ledger.get_balance(self.userReg.userentity.id), 1) self.assertEqual(self.ledger.get_balance(self.userOrg.userentity.id), 0) # issued currents not counted towards balances self.assertEqual( self.ledger.get_balance(self.orgTest.orgentity.id, 'org'), 0) def test_transact_user_user(self): ''' transact from one user to another and check balances ''' self.ledger.transact_currents( entity_type_from='user', entity_id_from=self.userReg.userentity.id, entity_type_to='user', entity_id_to=self.userBiz.userentity.id, action=self.actionUserReg, amount=1, ) self.assertEqual(self.ledger.get_balance(self.userReg.userentity.id), 0) self.assertEqual(self.ledger.get_balance(self.userBiz.userentity.id), 1) def test_insufficient_funds(self): ''' check appropriate exception raised when sender has insufficient funds ''' def _insufficient_funds_transaction(): self.ledger.transact_currents( entity_type_from='user', entity_id_from=self.userReg.userentity.id, entity_type_to='user', entity_id_to=self.userOrg.userentity.id, action=self.actionUserReg, amount=100) self.assertRaises(InsufficientFundsException, _insufficient_funds_transaction)
def test_user_entity_exists(self): ''' tests user entity was created ''' user = OcUser(self.userReg.id) self.assertIsNotNone(user.get_user_entity())
def test_partial_redemption_selenium(self): """ Partial redemption test. Action: User redeems Currents with Currents balance that's below the offer's current share (based on reported price) Expected result: - DB Transaction record created: pop_type is "receipt" if image is uploaded and "other" if text proof provided; currents_amount is {{ user_balance_available }} (equals user's currents available) - If provided, receipt image is uploaded to images/redeem/YYYY/MM/DD path on the server - DB TransactionAction record of action_type "pending" created - User's pending USD balance increased by {{ commissioned_amount_usd }} - Transaction summary is displayed in /profile: {{ redemption_date }} - You requested {{ commissioned_amount_usd }} for {{ user_balance_available }} from {{ orgname }} - Pending biz's Currents is increased by {{ user_balance_available }} - Transaction summary is displayed in /biz-admin: {{ redemption_date }} - {{ user.first_name user.last_name} purchased {{ offer.item }} for {{ price_reported }} and would receive {{ commissioned_amount_usd }} for {{ user_balance_available }} """ selenium = self.selenium redeem_price = 2000 exprected_usd_amount_gross = 20 exprected_usd_amount_net = 17 # logging in as biz admin to check initial state of pending currents self.biz_pending_currents_assertion(self.biz_admin, 0) # asserting initial currents for volunteer 1 self.volunteer_currents_assert(self.volunteer_1, self.initial_currents) force_login(self.volunteer_1, selenium, self.live_server_url) selenium.set_window_size(1024, 768) selenium.get('{}redeem-currents/1/'.format(self.live_server_url)) # STEP 1: Add description of purchase selenium.find_element_by_class_name('no-receipt-popup_open').click() text_to_input = 'this is a test description' selenium.find_element_by_id('no-proof-typed').send_keys(text_to_input) selenium.find_element_by_class_name('no-receipt-popup_close').click() text_area_text = selenium.find_element_by_id('id_redeem_no_proof').\ get_attribute('value') self.assertEqual(text_area_text, text_to_input) button = selenium.find_element_by_xpath( '/html/body/div[3]/div/form/div[1]/div[2]/a') selenium.execute_script("$(arguments[0]).click();", button) # STEP 2: Record price _selenium_wait_for( lambda: selenium.find_element_by_id('id_redeem_price')) selenium.find_element_by_id('id_redeem_price').send_keys(redeem_price) button = selenium.find_element_by_xpath( '/html/body/div[3]/div/form/div[1]/div[2]/a') selenium.execute_script("$(arguments[0]).click();", button) # STEP 3: Confirm exchange submit_button = selenium.find_element_by_xpath( '//*[@id="offer-3"]/div/div/div/input') _selenium_wait_for(lambda: submit_button) self.assertIn( '$<span class="dollars-total">{}</span>'.format( exprected_usd_amount_gross), selenium.page_source) self.assertIn( '$<span class="dollars-received">{}</span>'.format( exprected_usd_amount_net), selenium.page_source) selenium.execute_script("$(arguments[0]).click();", submit_button) # wait for redirection to user profile page _selenium_wait_for(lambda: selenium.find_element_by_class_name( 'earn-currents-popup_open')) # asserting currents and USD for volunteer_1 after submitting the form self.volunteer_currents_assert(self.volunteer_1, 0.0) self.assertEqual( OcUser(self.volunteer_1.id).get_balance_pending_usd(), exprected_usd_amount_net) # logging in as biz admin to check state of pending currents after # submitting the form self.biz_pending_currents_assertion(self.biz_admin, 1.0)
def setUp(self): """Set testing environment.""" # creating org self.org1 = OcOrg().setup_org(name="NPF_org_1", status="npf") # creating volunteers self.volunteer_1 = _create_test_user('volunteer_1') self.volunteer_2 = _create_test_user('volunteer_2') # getting full names of volunteers self.volunteer_1_full_name = self.volunteer_1.first_name + ' ' + self.volunteer_1.last_name self.volunteer_2_full_name = self.volunteer_2.first_name + ' ' + self.volunteer_2.last_name # creating an admins for NPF_orgs self.npf_admin_1 = _create_test_user('npf_admin_1', org=self.org1, is_org_admin=True) # creating a project self.project_1 = _create_project(self.org1, 'org1_project_1') # 1st event time = 3 hours datetime_start_1 = timezone.now() - timedelta(hours=4) datetime_end_1 = datetime_start_1 + timedelta(hours=3) # 2nd event time = 2 hours datetime_start_2 = timezone.now() - timedelta(hours=4) datetime_end_2 = datetime_start_2 + timedelta(hours=2) # setting 2 pending events _setup_volunteer_hours(self.volunteer_1, self.npf_admin_1, self.org1, self.project_1, datetime_start_1, datetime_end_1) _setup_volunteer_hours( self.volunteer_2, self.npf_admin_1, self.org1, self.project_1, datetime_start_2, datetime_end_2, ) # getting previous week start self.monday = ( timezone.now() - timedelta(days=timezone.now().weekday())).strftime("%-m-%-d-%Y") # oc instances self.oc_vol_1 = OcUser(self.volunteer_1.id) self.oc_vol_2 = OcUser(self.volunteer_2.id) # user entities self.user_enitity_id_vol_1 = UserEntity.objects.get( user=self.volunteer_1).id self.user_enitity_id_vol_2 = UserEntity.objects.get( user=self.volunteer_2).id # setting up client self.client = Client() self.client.login(username=self.npf_admin_1.username, password='******') self.response = self.client.get('/approve-hours/')
from csv import writer from datetime import datetime, timedelta from pytz import utc users = User.objects.filter(is_staff=False) ocledger = OcLedger() data = {} for user in users: try: us = user.usersettings except UserSettings.DoesNotExist: continue ocuser = OcUser(user.id) redemptions = ocuser.get_offers_redeemed() redemptions_req = filter(lambda x: x.action_type == 'req', redemptions) redemptions_app = filter(lambda x: x.action_type == 'app', redemptions) hours_req = ocuser.get_hours_requested() hours_app = ocuser.get_hours_approved() print user.id data[user.id] = { 'email': user.email, 'first_name': user.first_name.encode('utf-8'), 'last_name': user.last_name.encode('utf-8'),
def save(self, *args, **kwargs): super(TransactionAction, self).save(*args, **kwargs) from openCurrents.interfaces.ocuser import OcUser # check if the transaction action for selected transaction exists tr = self.transaction bizname = tr.biz_name if tr.biz_name else tr.offer.org.name # common transaction action email data email_vars = [{ 'name': 'ORG_NAME', 'content': bizname }, { 'name': 'AMOUNT', 'content': '%.2f' % tr.price_reported }, { 'name': 'TRANSACTION_ID', 'content': str(tr.id) }, { 'name': 'FNAME', 'content': tr.user.first_name }, { 'name': 'LNAME', 'content': tr.user.last_name }, { 'name': 'USER_EMAIL', 'content': tr.user.email }] template_name = None if self.action_type == 'req' and tr.offer.offer_type == 'gft': # send gift card out of stock email to bizdev sendTransactionalEmailBizDev('add-gift-card', email_vars) # merge vars and template name # for gift card out of stock to user template_name = 'gift-card-pending' elif self.action_type == 'app': oc_user = OcUser(tr.user.id) # transact cur from user to org Ledger.objects.create(entity_from=tr.user.userentity, entity_to=tr.offer.org.orgentity, currency='cur', amount=tr.currents_amount, transaction=self) # for cashback transactions, fiat ledger rec and confirmation email if tr.offer.offer_type == 'cbk': usd_amount = convert.cur_to_usd(tr.currents_amount, True) # transact usd from oC to user Ledger.objects.create(entity_from=OrgEntity.objects.get( org__name='openCurrents'), entity_to=tr.user.userentity, currency='usd', amount=usd_amount, transaction=self) # merge vars and template name # for cashback transaction approved email to user template_name = 'transaction-approved' amount_usd = '%.2f' % float(usd_amount) amound_cur = '%.2f' % float(tr.currents_amount) balance_cur = '%.2f' % float(oc_user.get_balance_available()) balance_usd = '%.2f' % float( oc_user.get_balance_available_usd()) email_vars = [{ 'name': 'BIZ_NAME', 'content': bizname }, { 'name': 'DOLLARS_REDEEMED', 'content': amount_usd }, { 'name': 'CURRENTS_REDEEMED', 'content': amound_cur }, { 'name': 'CURRENTS_AVAILABLE', 'content': balance_cur }, { 'name': 'DOLLARS_AVAILABLE', 'content': balance_usd }] elif tr.offer.offer_type == 'gft': if not self.giftcard: raise Exception( 'Approved action must be linked to a gift card') if self.giftcard.is_redeemed: raise Exception('Gift card has already been redeemed') else: self.giftcard.is_redeemed = True self.giftcard.save() sendTransactionalEmailBizDev('gift-card-purchased', email_vars) # merge vars and template name # for giftcard email to user email_vars.extend([{ 'name': 'CODE', 'content': self.giftcard.code }, { 'name': 'GIFT_IMAGE_URL', 'content': self.giftcard.image.url }]) template_name = 'gift-card' # send transaction action email to user if template_name: sendTransactionalEmailUser(template_name, email_vars, tr.user.email)
def __init__(self, userid): self.userid = userid self.user = OcUser(self.userid).get_user() self.orgusers = OrgUser.objects.filter(user__id=userid)
class TestApproveHoursOneWeek(TestCase): """Collection of tests for time records within one week.""" def setUp(self): """Set testing environment.""" # creating org self.org1 = OcOrg().setup_org(name="NPF_org_1", status="npf") # creating volunteers self.volunteer_1 = _create_test_user('volunteer_1') self.volunteer_2 = _create_test_user('volunteer_2') # getting full names of volunteers self.volunteer_1_full_name = self.volunteer_1.first_name + ' ' + self.volunteer_1.last_name self.volunteer_2_full_name = self.volunteer_2.first_name + ' ' + self.volunteer_2.last_name # creating an admins for NPF_orgs self.npf_admin_1 = _create_test_user('npf_admin_1', org=self.org1, is_org_admin=True) # creating a project self.project_1 = _create_project(self.org1, 'org1_project_1') # 1st event time = 3 hours datetime_start_1 = timezone.now() - timedelta(hours=4) datetime_end_1 = datetime_start_1 + timedelta(hours=3) # 2nd event time = 2 hours datetime_start_2 = timezone.now() - timedelta(hours=4) datetime_end_2 = datetime_start_2 + timedelta(hours=2) # setting 2 pending events _setup_volunteer_hours(self.volunteer_1, self.npf_admin_1, self.org1, self.project_1, datetime_start_1, datetime_end_1) _setup_volunteer_hours( self.volunteer_2, self.npf_admin_1, self.org1, self.project_1, datetime_start_2, datetime_end_2, ) # getting previous week start self.monday = ( timezone.now() - timedelta(days=timezone.now().weekday())).strftime("%-m-%-d-%Y") # oc instances self.oc_vol_1 = OcUser(self.volunteer_1.id) self.oc_vol_2 = OcUser(self.volunteer_2.id) # user entities self.user_enitity_id_vol_1 = UserEntity.objects.get( user=self.volunteer_1).id self.user_enitity_id_vol_2 = UserEntity.objects.get( user=self.volunteer_2).id # setting up client self.client = Client() self.client.login(username=self.npf_admin_1.username, password='******') self.response = self.client.get('/approve-hours/') def test_logged_hours_displayed(self): self.assertEqual(self.response.status_code, 200) # digging into response dictionaries for k in self.response.context[0]['week'][0]: self.assertEqual(2, len(self.response.context[0]['week'][0][k])) self.assertEqual( 3, len(self.response.context[0]['week'][0][k][ self.volunteer_1.email])) self.assertEqual( 3.0, self.response.context[0]['week'][0][k][ self.volunteer_1.email]['Total']) self.assertEqual( self.volunteer_1_full_name, self.response.context[0]['week'][0] [k][self.volunteer_1.email]['name']) self.assertEqual( 3, len(self.response.context[0]['week'][0][k][ self.volunteer_2.email])) self.assertEqual( 2.0, self.response.context[0]['week'][0][k][ self.volunteer_2.email]['Total']) self.assertEqual( self.volunteer_2_full_name, self.response.context[0]['week'][0] [k][self.volunteer_2.email]['name']) def test_logged_hours_accept(self): self.assertEqual(self.response.status_code, 200) org_admin_response = self.client.get('/org-admin/') self.assertEqual(org_admin_response.status_code, 200) # checking pending hours before approving self.assertDictEqual( org_admin_response.context['hours_pending_by_admin'], {self.npf_admin_1: 5.0}) self.assertEqual( 0, len(AdminActionUserTime.objects.filter(action_type='app'))) self.assertEqual( 2, len(AdminActionUserTime.objects.filter(action_type='req'))) # checking total approved hours self.assertEqual(org_admin_response.context['issued_by_all'], 0) # checking initial balance self.assertEqual(0, len(self.oc_vol_1.get_hours_approved())) self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_1)) self.assertEqual(0, len(self.oc_vol_2.get_hours_approved())) self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_2)) # approving hours self.response = self.client.post( '/approve-hours/', { 'post-data': self.volunteer_1.username + ':1:' + self.monday + ',' + self.volunteer_2.username + ':1:' + self.monday }) # return to org-amdin after approving self.assertRedirects(self.response, '/org-admin/2/0/', status_code=302) # assert the creation of the corresponding usertimelog and adminaction records self.assertEqual( 2, len(AdminActionUserTime.objects.filter(action_type='app'))) self.assertEqual( 0, len(AdminActionUserTime.objects.filter(action_type='req'))) self.assertEqual( 1, len( UserTimeLog.objects.filter(user=self.volunteer_1).filter( is_verified=True))) self.assertEqual( 1, len( AdminActionUserTime.objects.filter( usertimelog__user=self.volunteer_1).filter( action_type='app'))) self.assertEqual( 1, len( UserTimeLog.objects.filter(user=self.volunteer_2).filter( is_verified=True))) self.assertEqual( 1, len( AdminActionUserTime.objects.filter( usertimelog__user=self.volunteer_2).filter( action_type='app'))) # checking ledger records ledger_query = Ledger.objects.all() self.assertEqual(2, len(ledger_query)) # asserting the first user self.assertEqual( 1, len(ledger_query.filter( action__usertimelog__user=self.volunteer_1))) self.assertEqual( 'cur', ledger_query.get( action__usertimelog__user=self.volunteer_1).currency) self.assertEqual( 3, ledger_query.get( action__usertimelog__user=self.volunteer_1).amount) self.assertEqual( True, ledger_query.get( action__usertimelog__user=self.volunteer_1).is_issued) self.assertEqual(1, len(self.oc_vol_1.get_hours_approved())) self.assertEqual(3, OcLedger().get_balance(self.user_enitity_id_vol_1)) # asserting the 2nd user self.assertEqual( 1, len(ledger_query.filter( action__usertimelog__user=self.volunteer_2))) self.assertEqual( 'cur', ledger_query.get( action__usertimelog__user=self.volunteer_2).currency) self.assertEqual( 2, ledger_query.get( action__usertimelog__user=self.volunteer_2).amount) self.assertEqual( True, ledger_query.get( action__usertimelog__user=self.volunteer_2).is_issued) self.assertEqual(1, len(self.oc_vol_2.get_hours_approved())) self.assertEqual(2, OcLedger().get_balance(self.user_enitity_id_vol_2)) def test_logged_hours_declined(self): self.assertEqual(self.response.status_code, 200) org_admin_response = self.client.get('/org-admin/') self.assertEqual(org_admin_response.status_code, 200) # checking pending hours before declining self.assertDictEqual( org_admin_response.context['hours_pending_by_admin'], {self.npf_admin_1: 5.0}) # checking total approved hours self.assertEqual(org_admin_response.context['issued_by_all'], 0) # checking initial balance self.assertEqual(0, len(self.oc_vol_1.get_hours_approved())) self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_1)) self.assertEqual(0, len(self.oc_vol_2.get_hours_approved())) self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_2)) self.response = self.client.post( '/approve-hours/', { 'post-data': self.volunteer_1.username + ':0:' + self.monday + ',' + self.volunteer_2.username + ':0:' + self.monday }) # return to org-amdin after declining self.assertRedirects(self.response, '/org-admin/0/2/', status_code=302) # assert the creation of the corresponding usertimelog and adminaction records self.assertEqual( 0, len(AdminActionUserTime.objects.filter(action_type='app'))) self.assertEqual( 0, len(AdminActionUserTime.objects.filter(action_type='app'))) self.assertEqual( 2, len(AdminActionUserTime.objects.filter(action_type='dec'))) self.assertEqual( 1, len( UserTimeLog.objects.filter(user=self.volunteer_1).filter( is_verified=False))) self.assertEqual( 1, len( AdminActionUserTime.objects.filter( usertimelog__user=self.volunteer_1).filter( action_type='dec'))) self.assertEqual( 1, len( UserTimeLog.objects.filter(user=self.volunteer_2).filter( is_verified=False))) self.assertEqual( 1, len( AdminActionUserTime.objects.filter( usertimelog__user=self.volunteer_2).filter( action_type='dec'))) # checking ledger records ledger_query = Ledger.objects.all() self.assertEqual(0, len(ledger_query)) # asserting the first user self.assertEqual( 0, len(ledger_query.filter( action__usertimelog__user=self.volunteer_1))) self.assertEqual(0, len(self.oc_vol_1.get_hours_approved())) self.assertEqual(0, len(self.oc_vol_1.get_hours_approved())) self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_1)) # asserting the 2nd user self.assertEqual( 0, len(ledger_query.filter( action__usertimelog__user=self.volunteer_2))) self.assertEqual(0, len(self.oc_vol_2.get_hours_approved())) self.assertEqual(0, len(self.oc_vol_2.get_hours_approved())) self.assertEqual(0, OcLedger().get_balance(self.user_enitity_id_vol_1))