def test_address_has_no_lat_long(self): mi = Location(name=us.states.lookup("MI").name, sector="federal").save() address = Address(state="MI").save() res = connect_to_state_districts.apply_async( kwargs={'object_uuid': address.object_uuid}) self.assertFalse(res.result) mi.delete() address.delete()
class TestAddress(TestCase): def setUp(self): self.address = Address(city="Wixom", state="MI").save() try: Location.nodes.get(name="Wixom").delete() except (Location.DoesNotExist, DoesNotExist): pass except MultipleNodesReturned: query = 'MATCH (a:Location {name:"Wixom"}) RETURN a' res, _ = db.cypher_query(query) for location in res[0]: Location.inflate(location).delete() try: self.state = Location.nodes.get(name="Michigan") except MultipleNodesReturned: query = 'MATCH (a:Location {name:"Michigan"}) RETURN a' res, _ = db.cypher_query(query) for location in res[0]: Location.inflate(location).delete() except (Location.DoesNotExist, DoesNotExist): self.state = Location(name="Michigan").save() def test_set_encompassing_no_nodes(self): res = self.address.set_encompassing() city = Location.nodes.get(name="Wixom") self.assertTrue(res.encompassed_by.is_connected(city)) city.delete() def test_set_encompassing_city_exists(self): city = Location(name="Wixom").save() city.encompassed_by.connect(self.state) self.state.encompasses.connect(city) res = self.address.set_encompassing() self.assertTrue(res.encompassed_by.is_connected(city)) city.delete() def test_multiple_cities_same_name(self): address = Address(city="Redford", state="Michigan").save() city = Location(name="Redford").save() city2 = Location(name="Redford").save() try: new_state = Location.nodes.get(name="Washington") except (Location.DoesNotExist, DoesNotExist): new_state = Location(name="Washington").save() self.state.encompasses.connect(city) city.encompassed_by.connect(self.state) city2.encompassed_by.connect(new_state) new_state.encompasses.connect(city2) res = address.set_encompassing() self.assertTrue(res.encompassed_by.is_connected(city)) city.delete() city2.delete() address.delete()
def test_address_has_lat_long_outside_usa(self): mi = Location(name=us.states.lookup("MI").name, sector="federal").save() # lat/long of Greenwich UK address = Address(state="MI", latitude=51.4800, longitude=0.0000).save() res = connect_to_state_districts.apply_async( kwargs={'object_uuid': address.object_uuid}) self.assertTrue(res.result) mi.delete() address.delete()
def get_address(self): query = 'MATCH (p:Pleb {username: "******"})-[:LIVES_AT]->(a:Address) ' \ 'RETURN a' % self.username res, _ = db.cypher_query(query) try: return Address.inflate(res.one) except AttributeError: return None
def test_multiple_cities_same_name(self): address = Address(city="Redford", state="Michigan").save() city = Location(name="Redford").save() city2 = Location(name="Redford").save() try: new_state = Location.nodes.get(name="Washington") except (Location.DoesNotExist, DoesNotExist): new_state = Location(name="Washington").save() self.state.encompasses.connect(city) city.encompassed_by.connect(self.state) city2.encompassed_by.connect(new_state) new_state.encompasses.connect(city2) res = address.set_encompassing() self.assertTrue(res.encompassed_by.is_connected(city)) city.delete() city2.delete() address.delete()
def setUp(self): query = 'MATCH (a) OPTIONAL MATCH (a)-[r]-() DELETE a, r' db.cypher_query(query) self.unit_under_test_name = 'address' self.email = "*****@*****.**" self.pleb = create_user_util_test(self.email) self.user = User.objects.get(email=self.email) PublicOfficial(bioguideid=str(uuid1()), title="President", gt_id=str(uuid1())).save() self.address = Address(street="3295 Rio Vista St", city="Commerce Township", state="MI", postal_code="48382", country="US", congressional_district="11") self.address.save() self.pleb.address.connect(self.address) self.url = "http://testserver"
def test_create_state_districts(self): mi = Location(name=us.states.lookup("MI").name, sector="federal").save() address = Address(state="MI", latitude=42.532020, longitude=-83.496500).save() lower = Location(name='38', sector='state_lower').save() upper = Location(name='15', sector='state_upper').save() mi.encompasses.connect(lower) lower.encompassed_by.connect(mi) mi.encompasses.connect(upper) upper.encompassed_by.connect(mi) res = connect_to_state_districts.apply_async( kwargs={'object_uuid': address.object_uuid}) self.assertTrue(res.result) self.assertTrue(lower in address.encompassed_by) self.assertTrue(upper in address.encompassed_by) mi.delete() address.delete() upper.delete() lower.delete()
def setUp(self): self.address = Address(city="Wixom", state="MI").save() try: Location.nodes.get(name="Wixom").delete() except (Location.DoesNotExist, DoesNotExist): pass except MultipleNodesReturned: query = 'MATCH (a:Location {name:"Wixom"}) RETURN a' res, _ = db.cypher_query(query) for location in res[0]: Location.inflate(location).delete() try: self.state = Location.nodes.get(name="Michigan") except MultipleNodesReturned: query = 'MATCH (a:Location {name:"Michigan"}) RETURN a' res, _ = db.cypher_query(query) for location in res[0]: Location.inflate(location).delete() except (Location.DoesNotExist, DoesNotExist): self.state = Location(name="Michigan").save()
def test_quest_settings_with_address(self): address = Address(street="3295 Rio Vista St", city="Commerce Township", state="MI", postal_code="48382", country="US", congressional_district="11").save() self.quest.address.connect(address) self.client.login(username=self.user.username, password=self.password) url = reverse('quest_manage_settings', kwargs={'username': self.user.username}) res = self.client.get(url) self.assertEqual(res.status_code, status.HTTP_302_FOUND)
def test_create_state_districts_already_exist(self): mi = Location(name=us.states.lookup("MI").name, sector="federal").save() address = Address(state="MI", latitude=42.532020, longitude=-83.496500).save() upper = Location(name="15", sector="state_upper").save() lower = Location(name="38", sector="state_lower").save() address.encompassed_by.connect(lower) address.encompassed_by.connect(upper) mi.encompasses.connect(upper) upper.encompassed_by.connect(mi) mi.encompasses.connect(lower) lower.encompassed_by.connect(mi) res = connect_to_state_districts.apply_async( kwargs={'object_uuid': address.object_uuid}) self.assertTrue(res.result) query = 'MATCH (l:Location {name:"38", sector:"state_lower"}), ' \ '(l2:Location {name:"15", sector:"state_upper"}) RETURN l, l2' res, _ = db.cypher_query(query) lower = Location.inflate(res[0].l) upper = Location.inflate(res[0].l2) self.assertTrue(lower in address.encompassed_by) self.assertTrue(upper in address.encompassed_by) res = connect_to_state_districts.apply_async( kwargs={'object_uuid': address.object_uuid}) self.assertTrue(res.result) query = 'MATCH (l:Location {name:"38", sector:"state_lower"}), ' \ '(l2:Location {name:"15", sector:"state_upper"}) RETURN l, l2' res, _ = db.cypher_query(query) self.assertEqual(len(res[0]), 2) # assert only two nodes returned self.assertEqual(lower, Location.inflate(res[0].l)) # assert only one lower node self.assertEqual(upper, Location.inflate(res[0].l2)) # assert only one upper node mi.delete() address.delete() upper.delete() lower.delete()
def setUp(self): settings.CELERY_ALWAYS_EAGER = True query = "MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE n,r" db.cypher_query(query) cache.clear() self.unit_under_test_name = 'quest' self.email = "*****@*****.**" self.pleb = create_user_util_test(self.email) self.user = User.objects.get(email=self.email) self.url = "http://testserver" self.quest = Quest(about='Test Bio', owner_username=self.pleb.username).save() self.quest.editors.connect(self.pleb) self.quest.moderators.connect(self.pleb) self.usa = Location(name="United States of America").save() self.michigan = Location(name="Michigan").save() self.d11 = Location(name="11", sector="federal").save() self.usa.encompasses.connect(self.michigan) self.michigan.encompassed_by.connect(self.usa) self.michigan.encompasses.connect(self.d11) self.d11.encompassed_by.connect(self.michigan) self.address = Address(street="125 Glenwood Drive", city="Walled Lake", state="Michigan", postal_code="48390", country="USA", county="Oakland", congressional_district=11, validated=True).save() self.address.encompassed_by.connect(self.d11) self.quest.address.connect(self.address) cache.clear() self.stripe = stripe self.stripe.api_key = settings.STRIPE_SECRET_KEY stripe.api_version = settings.STRIPE_API_VERSION self.mission = Mission(owner_username=self.pleb.username, title=str(uuid1()), focus_name="advocacy", location_name="11").save() self.mission.location.connect(self.d11) self.quest.missions.connect(self.mission) self.email2 = "*****@*****.**" self.pleb2 = create_user_util_test(self.email2) self.user2 = User.objects.get(email=self.email2)
def general_settings(request): """ Displays the users profile_page. This is where we call the functions to determine who the senators are for the plebs state and which representative for the plebs district. Checks to see if the user currently accessing the page is the same user as the one who owns the page. If so it loads the page fully, if the user is a friend of the owner of the page then it allows them to see posts and comments on posts on the owners wall. If the user is neither the owner nor a friend then it only shows the users name, congressmen, reputation and profile pictures along with a button that allows them to send a friend request. :param request: :return: """ address_key = settings.ADDRESS_AUTH_ID query = 'MATCH (person:Pleb {username: "******"})' \ '-[r:LIVES_AT]->(house:Address) RETURN house' % ( request.user.username) try: res, col = db.cypher_query(query) address = AddressSerializer(Address.inflate(res[0][0]), context={ 'request': request }).data except (CypherException, ClientError): return redirect("500_Error") except IndexError: address = False try: query = 'MATCH (q:Quest {owner_username:"******"}) RETURN q' % ( request.user.username) res, _ = db.cypher_query(query) quest = QuestSerializer(Quest.inflate(res[0][0]), context={ 'request': request }).data except (DoesNotExist, Quest.DoesNotExist, IndexError): quest = None return render(request, 'settings/general_settings.html', { "address": address, "address_key": address_key, "quest": quest })
def update(self, instance, validated_data): from sb_base.serializers import validate_is_owner logger.critical(validated_data) logger.critical('Updating Quest') if instance.owner_username == "andrea_nickelson": if validated_data.get('ssn', None) is not None: instance.ssn_temp = validated_data.get('ssn', "") if validated_data.get('routing_number', None) is not None: instance.routing_number_temp = validated_data.get( 'routing_number', "") if validated_data.get('account_number', None) is not None: instance.bank_account_temp = validated_data.get( 'account_number', "") instance.save() return instance request = self.context.get('request', None) validate_is_owner(request, instance, self.context.get('secret')) stripe.api_key = settings.STRIPE_SECRET_KEY stripe.api_version = settings.STRIPE_API_VERSION address = request.data.get('address') if address is not None: address_serializer = AddressSerializer( data=address, context={'request', request}) address_serializer.is_valid(raise_exception=True) address = address_serializer.save() query = 'MATCH (a:Quest {object_uuid: "%s"}) ' \ 'OPTIONAL MATCH (a)-[r:LOCATED_AT]-(:Address) ' \ 'DELETE r' % instance.object_uuid res, _ = db.cypher_query(query) instance.address.connect(address) stripe_token = validated_data.pop('stripe_token', None) promotion_key = validated_data.pop('promotion_key', None) customer_token = validated_data.pop('customer_token', instance.customer_token) account_type = validated_data.get('account_type', instance.account_type) instance.stripe_account_type = validated_data.get( 'stripe_account_type', instance.stripe_account_type) instance.account_owner = validated_data.get('account_owner', instance.account_owner) initial_state = instance.active customer = None ein = validated_data.pop('ein', instance.ein) ssn = validated_data.pop('ssn', instance.ssn) # ** Standard Settings Update ** # Remove any dashes from the ssn input. if ssn is not None: ssn = ssn.replace('-', "") active = validated_data.pop('active', instance.active) if initial_state is False and active is True: serializer = IntercomEventSerializer( data={ 'event_name': "take-quest-live", 'username': instance.owner_username }) # Don't raise an error because we rather not notify intercom than # hold up the quest activation process if serializer.is_valid(): serializer.save() db.cypher_query( 'MATCH (quest:Quest {object_uuid: "%s"})-[:EMBARKS_ON]' '-(mission:Mission)-' '[:MUST_COMPLETE]->(task:OnboardingTask {title: "%s"}) ' 'SET task.completed=true RETURN task' % (instance.object_uuid, settings.BANK_SETUP_TITLE)) instance.active = active instance.title = empty_text_to_none( validated_data.pop('title', instance.title)) instance.facebook = clean_url( validated_data.get('facebook', instance.facebook)) instance.linkedin = clean_url( validated_data.get('linkedin', instance.linkedin)) instance.youtube = clean_url( validated_data.get('youtube', instance.youtube)) instance.twitter = clean_url( validated_data.get('twitter', instance.twitter)) if initial_state is True and active is False: remove_search_object(instance.object_uuid, "quest") # TODO make all missions inactive upon taking quest inactive instance.website = clean_url( validated_data.get('website', instance.website)) instance.about = empty_text_to_none( validated_data.get('about', instance.about)) if instance.about is not None: db.cypher_query( 'MATCH (quest:Quest {object_uuid: "%s"})-[:EMBARKS_ON]' '-(mission:Mission)-' '[:MUST_COMPLETE]->(task:OnboardingTask {title: "%s"}) ' 'SET task.completed=true RETURN task' % (instance.object_uuid, settings.QUEST_ABOUT_TITLE)) instance.wallpaper_pic = validated_data.get('wallpaper_pic', instance.wallpaper_pic) if settings.DEFAULT_WALLPAPER not in instance.wallpaper_pic: db.cypher_query( 'MATCH (quest:Quest {object_uuid: "%s"})-[:EMBARKS_ON]' '-(mission:Mission)-' '[:MUST_COMPLETE]->(task:OnboardingTask {title: "%s"}) ' 'SET task.completed=true RETURN task' % (instance.object_uuid, settings.QUEST_WALLPAPER_TITLE)) instance.profile_pic = validated_data.get('profile_pic', instance.profile_pic) owner = Pleb.get(username=instance.owner_username) # ** Customer Creation/Card Assignment If Provided ** if customer_token is not None: # Customers must provide a credit card for us to create a customer # with stripe. Get the credit card # and create a customer instance # so we can charge it in the future. if instance.stripe_customer_id is None: customer = stripe.Customer.create( description="Customer for %s Quest" % instance.object_uuid, card=customer_token, email=owner.email) instance.stripe_customer_id = customer['id'] instance.stripe_default_card_id = customer['sources']['data'][ 0]['id'] else: customer = stripe.Customer.retrieve( instance.stripe_customer_id) card = customer.sources.create(source=customer_token) instance.stripe_default_card_id = card['id'] elif customer_token is None and account_type == "promotion": if instance.stripe_customer_id is None: customer = stripe.Customer.create( description="Customer for %s Quest" % instance.object_uuid, email=owner.email) instance.stripe_customer_id = customer['id'] # ** Account plan updating process ** if account_type != instance.account_type: if customer is None: customer = stripe.Customer.retrieve( instance.stripe_customer_id) if account_type == "paid": # if paid gets submitted create a subscription if it doesn't # already exist if instance.stripe_subscription_id is None: sub = customer.subscriptions.create(plan='quest_premium') instance.stripe_subscription_id = sub['id'] instance.application_fee = settings.STRIPE_PAID_ACCOUNT_FEE instance.account_type = account_type elif account_type == "promotion": if promotion_key in settings.PROMOTION_KEYS \ and settings.PRO_QUEST_PROMOTION: if datetime.now() < settings.PRO_QUEST_END_DATE: next_year = datetime.now() + relativedelta(years=+1) unix_stamp = time.mktime(next_year.timetuple()) # Only allow people without subscriptions to create # a new one with a trial. # TODO for existing customers we need to create # coupons through Stripe so that we don't have # duplicate subscriptions associated with one # user. if instance.stripe_subscription_id is None: sub = customer.subscriptions.create( plan='quest_premium', trial_end=int(unix_stamp)) instance.stripe_subscription_id = sub['id'] instance.application_fee = \ settings.STRIPE_PAID_ACCOUNT_FEE else: account_type = instance.account_type else: account_type = instance.account_type elif account_type == "free": # if we get a free submission and the subscription is already # set cancel it. if instance.stripe_subscription_id is not None: customer.subscriptions.retrieve( instance.stripe_subscription_id).delete() instance.stripe_subscription_id = None instance.application_fee = settings.STRIPE_FREE_ACCOUNT_FEE instance.account_type = account_type instance.account_type = account_type # ** Stripe update Address ** if address is not None: account = stripe.Account.retrieve(instance.stripe_id) street_additional = empty_text_to_none(address.street_additional) account.legal_entity.address.line1 = address.street account.legal_entity.address.line2 = street_additional account.legal_entity.address.city = address.city account.legal_entity.address.state = address.state account.legal_entity.address.postal_code = address.postal_code account.legal_entity.address.country = "US" account.save() # ** Managed Account Setup ** if stripe_token is not None: if instance.stripe_id is None or instance.stripe_id == "Not Set": account = stripe.Account.create(managed=True, country="US", email=owner.email) instance.stripe_id = account['id'] else: account = stripe.Account.retrieve(instance.stripe_id) try: account.external_accounts.create(external_account=stripe_token, default_for_currency=True) except InvalidRequestError: raise serializers.ValidationError( detail={ "detail": "Looks like we're having server " "issues, please contact us using the " "bubble in the bottom right", "status_code": status.HTTP_400_BAD_REQUEST }) query = 'MATCH (a:Quest {owner_username: "******"})' \ '-[:LOCATED_AT]->(b:Address) ' \ 'RETURN b' % instance.owner_username res, _ = db.cypher_query(query) account_address = Address.inflate(res.one) if not instance.tos_acceptance: request = self.context.get('request', None) if request is not None: x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') account.tos_acceptance.ip = ip account.tos_acceptance.date = int(time.time()) instance.tos_acceptance = True account.legal_entity.additional_owners = [] account.legal_entity.personal_id_number = ssn if ein: account.legal_entity.business_tax_id = ein account.legal_entity.first_name = owner.first_name account.legal_entity.last_name = owner.last_name if instance.account_owner != "" \ and instance.account_owner is not None: account.business_name = instance.account_owner account.legal_entity.business_name = instance.account_owner stripe_account_type = instance.stripe_account_type if stripe_account_type == "business": stripe_account_type = 'company' account.legal_entity.type = stripe_account_type street_additional = empty_text_to_none( account_address.street_additional) account.legal_entity.address.line1 = account_address.street account.legal_entity.address.line2 = street_additional account.legal_entity.address.city = account_address.city account.legal_entity.address.state = account_address.state account.legal_entity.address.postal_code = \ account_address.postal_code account.legal_entity.address.country = "US" owner = Pleb.get(username=request.user.username) account.legal_entity.dob.day = owner.date_of_birth.day account.legal_entity.dob.month = owner.date_of_birth.month account.legal_entity.dob.year = owner.date_of_birth.year try: account = account.save() except stripe.InvalidRequestError: raise serializers.ValidationError( detail={ "detail": "Sorry, you can't change your " "Social Security Number after you " "have been verified. Please contact " "support at [email protected] " "or by using the " "bubble in the bottom right.", "status_code": status.HTTP_400_BAD_REQUEST }) # Default to pending to make sure customer doesn't think nothing # is happening on a slow update from Stripe. We can revert back # to unverified if Stripe alerts us to it. verification = "pending" if account.legal_entity.verification.status == "verified": verification = account.legal_entity.verification.status instance.account_verified = verification instance.last_four_soc = ssn[-4:] instance.save() cache.delete("%s_quest" % instance.owner_username) # ** Search Update ** if instance.active: return super(QuestSerializer, self).update(instance, validated_data) return instance
class AddressEndpointTests(APITestCase): def setUp(self): query = 'MATCH (a) OPTIONAL MATCH (a)-[r]-() DELETE a, r' db.cypher_query(query) self.unit_under_test_name = 'address' self.email = "*****@*****.**" self.pleb = create_user_util_test(self.email) self.user = User.objects.get(email=self.email) PublicOfficial(bioguideid=str(uuid1()), title="President", gt_id=str(uuid1())).save() self.address = Address(street="3295 Rio Vista St", city="Commerce Township", state="MI", postal_code="48382", country="US", congressional_district="11") self.address.save() self.pleb.address.connect(self.address) self.url = "http://testserver" def test_unauthorized(self): url = reverse('address-list') data = {} response = self.client.post(url, data, format='json') self.assertIn( response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN]) def test_missing_data(self): self.client.force_authenticate(user=self.user) url = reverse('address-list') data = {'this': ['This field is required.']} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_save_int_data(self): self.client.force_authenticate(user=self.user) url = reverse('address-list') response = self.client.post(url, 98897965, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_save_string_data(self): self.client.force_authenticate(user=self.user) url = reverse('address-list') response = self.client.post(url, 'asfonosdnf', format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_save_list_data(self): self.client.force_authenticate(user=self.user) url = reverse('address-list') response = self.client.post(url, [], format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_save_float_data(self): self.client.force_authenticate(user=self.user) url = reverse('address-list') response = self.client.post(url, 1.010101010, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) def test_create_on_detail(self): self.client.force_authenticate(user=self.user) url = reverse('address-detail', kwargs={'object_uuid': self.address.object_uuid}) data = {} response = self.client.post(url, data=data, format='json') response_data = { 'status_code': status.HTTP_405_METHOD_NOT_ALLOWED, 'detail': 'Method "POST" not allowed.' } self.assertEqual(response.data, response_data) self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) def test_delete(self): self.client.force_authenticate(user=self.user) url = reverse('address-list') response = self.client.delete(url, format='json') self.assertEqual(response.data['status_code'], status.HTTP_405_METHOD_NOT_ALLOWED) self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) self.assertEqual(response.data['detail'], 'Method "DELETE" not allowed.') def test_get_id(self): self.client.force_authenticate(user=self.user) url = reverse('address-detail', kwargs={'object_uuid': self.address.object_uuid}) response = self.client.get(url, format='json') self.assertEqual(self.address.object_uuid, response.data['id']) def test_get_type(self): self.client.force_authenticate(user=self.user) url = reverse('address-detail', kwargs={'object_uuid': self.address.object_uuid}) response = self.client.get(url, format='json') self.assertEqual('address', response.data['type']) def test_get_street(self): self.client.force_authenticate(user=self.user) url = reverse('address-detail', kwargs={'object_uuid': self.address.object_uuid}) response = self.client.get(url, format='json') self.assertEqual('3295 Rio Vista St', response.data['street']) def test_get_street_additional(self): self.client.force_authenticate(user=self.user) url = reverse('address-detail', kwargs={'object_uuid': self.address.object_uuid}) response = self.client.get(url, format='json') self.assertIsNone(response.data['street_additional']) def test_get_city(self): self.client.force_authenticate(user=self.user) url = reverse('address-detail', kwargs={'object_uuid': self.address.object_uuid}) response = self.client.get(url, format='json') self.assertEqual(response.data['city'], "Commerce Township") def test_get_state(self): self.client.force_authenticate(user=self.user) url = reverse('address-detail', kwargs={'object_uuid': self.address.object_uuid}) response = self.client.get(url, format='json') self.assertEqual(response.data['state'], 'MI') def test_get_postal_code(self): self.client.force_authenticate(user=self.user) url = reverse('address-detail', kwargs={'object_uuid': self.address.object_uuid}) response = self.client.get(url, format='json') self.assertEqual(response.data['postal_code'], "48382") def test_get_congressional_district(self): self.client.force_authenticate(user=self.user) url = reverse('address-detail', kwargs={'object_uuid': self.address.object_uuid}) response = self.client.get(url, format='json') self.assertEqual(response.data['congressional_district'], 11) def test_get_validated(self): self.client.force_authenticate(user=self.user) url = reverse('address-detail', kwargs={'object_uuid': self.address.object_uuid}) response = self.client.get(url, format='json') self.assertFalse(response.data['validated']) def test_address_list(self): self.client.force_authenticate(user=self.user) url = reverse('address-list') response = self.client.get(url, format='json') self.assertGreater(response.data['count'], 0) def test_create_address_with_patch(self): self.client.force_authenticate(user=self.user) url = reverse('address-list') data = { 'city': "Walled Lake", 'longitude': -83.48016, 'state': "MI", 'street': "300 Eagle Pond Dr.", 'postal_code': "48390-3071", 'congressional_district': "11", 'latitude': 42.54083 } response = self.client.patch(url, data=data, format='json') self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) def test_create_address(self): self.client.force_authenticate(user=self.user) url = reverse('address-list') data = { 'city': "Walled Lake", 'longitude': -83.48016, 'state': "MI", 'street': "300 Eagle Pond Dr.", 'postal_code': "48390-3071", 'congressional_district': "11", 'latitude': 42.54083 } response = self.client.post(url, data=data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data['city'], 'Walled Lake') def test_create_address_with_mistakes(self): self.client.force_authenticate(user=self.user) url = reverse('address-list') data = { 'city': "Walled Lake", 'longitude': -83.48016, 'state': "MI.- ", 'street': "300 Eagle Pond Dr.", 'postal_code': "48390-3071", 'congressional_district': "11", 'latitude': 42.54083 } response = self.client.post(url, data=data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data['state'], 'Michigan') def test_update(self): self.client.force_authenticate(user=self.user) url = reverse('address-detail', kwargs={'object_uuid': self.address.object_uuid}) data = { 'city': "Walled Lake", 'longitude': -83.48016, 'state': "MI", 'street': "300 Eagle Pond Dr.", 'postal_code': "48390-3071", 'congressional_district': "11", 'latitude': 42.54083 } response = self.client.put(url, data=data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) def test_update_no_matching_location(self): settings.CELERY_ALWAYS_EAGER = True self.client.force_authenticate(user=self.user) url = reverse('address-detail', kwargs={'object_uuid': self.address.object_uuid}) data = { 'city': "Walled Lake", 'longitude': -83.48016, 'state': "MI", 'street': "300 Eagle Pond Dr.", 'postal_code': "48390-3071", 'congressional_district': "100", 'latitude': 42.54083 } response = self.client.put(url, data=data, format='json') settings.CELERY_ALWAYS_EAGER = False self.assertEqual(response.status_code, status.HTTP_200_OK) def test_update_with_matching_location(self): settings.CELERY_ALWAYS_EAGER = True self.client.force_authenticate(user=self.user) url = reverse('address-detail', kwargs={'object_uuid': self.address.object_uuid}) state = Location(name="Michigan").save() district = Location(name="10", sector="federal").save() state.encompasses.connect(district) district.encompassed_by.connect(state) data = { 'city': "Walled Lake", 'longitude': -83.48016, 'state': "MI", 'street': "300 Eagle Pond Dr.", 'postal_code': "48390-3071", 'congressional_district': "10", 'latitude': 42.54083 } response = self.client.put(url, data=data, format='json') settings.CELERY_ALWAYS_EAGER = False address = Address.nodes.get(object_uuid=response.data['id']) self.assertIn(district, address.encompassed_by)
def get(self, request, username=None): from sb_missions.neo_models import Mission from sb_missions.serializers import MissionSerializer from sb_missions.utils import order_tasks query = 'MATCH (person:Pleb {username: "******"})' \ '-[r:IS_WAGING]->(quest:Quest) WITH quest ' \ 'OPTIONAL MATCH (quest)-[:EMBARKS_ON]->(missions:Mission) ' \ 'RETURN quest, missions ORDER BY missions.created DESC' % ( request.user.username) try: res, _ = db.cypher_query(query) if res.one is None: return redirect("404_Error") except (CypherException, ClientError): return redirect("500_Error") res.one.quest.pull() quest_obj = Quest.inflate(res.one.quest) quest_ser = QuestSerializer(quest_obj, context={ 'request': request }).data quest_ser['account_type'] = quest_obj.account_type if res.one.missions is None: mission_link = reverse('select_mission') mission_active = False onboarding_sort = [] mission_obj = None onboarding_done = 0 else: mission_obj = Mission.inflate(res[0].missions) mission_link = reverse('mission_settings', kwargs={ "object_uuid": mission_obj.object_uuid, "slug": slugify(mission_obj.get_mission_title()) }) mission_active = mission_obj.active onboarding_sort, completed_count = order_tasks( mission_obj.object_uuid) onboarding_done = int( (float(completed_count) / float(len(onboarding_sort))) * 100) res, _ = db.cypher_query('MATCH (a:Quest {owner_username: "******"})' '-[:LOCATED_AT]->(b:Address) ' 'RETURN b' % quest_obj.owner_username) if res.one is not None: address = Address.inflate(res.one) else: address = None if self.template_name == "manage/quest_banking.html" \ and address is None: return redirect('account_setup') if self.template_name == "manage/quest_settings.html": return redirect('general_settings') return render( request, self.template_name, { "quest": quest_ser, "mission_link": mission_link, "mission_active": mission_active, "mission": MissionSerializer(mission_obj, context={ "request": request }).data, "address": address, "onboarding_top_3": onboarding_sort[:3], "onboarding_rest": onboarding_sort[3:], "onboarding_done": onboarding_done })