示例#1
0
def test_error_mapping():
    responses.add(
        responses.GET,
        "https://localhost:8000/mobilize/v1/organizations/1/events",
        body=json.dumps(NOT_FOUND_RESPONSE),
        status=404,
    )
    with pytest.raises(MobilizeAmericaAPIException) as exec_info:
        mobilize_america.get_global_client().list_organization_events()
    assert exec_info.value.response["error"]["detail"] == "Not found."
示例#2
0
 def sync_to_mobilize_america(self):
     if not self.ma_creation_successful and (self.email and self.zip5):
         try:
             referrer = Referrer(
                 utm_source=self.source) if self.source else None
             self.ma_response, timeslots_signed_up = get_global_client(
             ).create_event_attendance(
                 self.ma_event_id,
                 list(self.ma_timeslot_ids),
                 person=AttendanceRequestPerson(
                     given_name=self.given_name,
                     family_name=self.family_name,
                     email_address=self.email,
                     postal_code=self.zip5,
                     phone_number=str(self.phone),
                 ),
                 referrer=referrer,
                 honor_ma_attendance=self.honor_ma_attendance,
             )
             self.ma_creation_successful = True
             self.signed_up_via_shifter = timeslots_signed_up
         except MobilizeAmericaAPIException as e:
             self.ma_response = e.response
             self.ma_creation_successful = False
         self.save()
     return self.ma_creation_successful, self.ma_response
示例#3
0
def test_create_event_attendance_already_exists():
    responses.add(
        responses.GET,
        f"https://*****:*****@elizabethwarren.com",
            postal_code="11238",
        ),
    )
    assert len(responses.calls) == 1
示例#4
0
    def handle(self, *args, **options):
        logging.info(f"Starting Mobilize America event import")
        event_count = 0

        for visibility in VISIBILITY_TYPES:
            created_events = []
            updated_events = []
            logging.info(f"Indexing {visibility} events")
            params = {"timeslot_start": "gte_now", "visibility": visibility}
            res = get_global_client().list_organization_events(params=params)
            page_count = 0
            events_for_visibiity = 0
            for page in res:
                logging.info(f"PAGE: {page_count}")
                page_count += 1
                for event in page["data"]:
                    events_for_visibiity += 1
                    shifter_event, created = MobilizeAmericaEvent.objects.update_or_create_from_json(
                        event
                    )
                    if created:
                        created_events.append(str(shifter_event.id))
                    else:
                        updated_events.append(str(shifter_event.id))
            event_count += events_for_visibiity
            if events_for_visibiity == MA_EVENT_GET_MAX:
                # telemetry.event(
                #     "Shifter Mobilize America Event Import at 1000",
                #     page_count=page_count,
                #     visibility=visibility,
                #     event_count=events_for_visibiity,
                # )
            created_event_ids_string = ", ".join(created_events)
            logging.info(
                f"Created the following {visibility} events: {created_event_ids_string}"
            )
            updated_event_ids_string = ", ".join(updated_events)
            logging.info(
                f"Updated the following {visibility} events: {updated_event_ids_string}"
            )

        # Find all the events that were not updated in the last 20 minutes
        # and mark them as inactive in the database
        updated_at_cut_off = timezone.now() - timedelta(minutes=20)
        MobilizeAmericaEvent.objects.filter(updated_at__lte=updated_at_cut_off).update(
            is_active=False
        )
        return f"Loaded events: {event_count}"
    def find_events(
        cls,
        limit,
        zip5=None,
        max_dist=None,
        tag_ids=None,
        timeslot_start=None,
        timeslot_end=None,
        event_types=None,
        is_virtual=False,
        states=None,
    ) -> List[Dict[str, Any]]:
        if timeslot_start:
            timeslot_start_param = f"gte_{int(timeslot_start.timestamp())}"
        else:
            timeslot_start_param = "gte_now"
        if timeslot_end:
            timeslot_end_param = f"lte_{int(timeslot_end.timestamp())}"
        else:
            timeslot_end_param = None

        if states:
            logging.warning(
                "Cannot pass states param when using Mobilize America Recomendation Strategy"
            )

        params = {
            "timeslot_start": timeslot_start_param,
            "tag_id": tag_ids,
            "event_types": event_types,
        }
        if timeslot_end_param:
            params["timeslot_end"] = timeslot_end_param

        if is_virtual:
            params["is_virtual"] = True
        else:
            params["zipcode"] = zip5
            params["max_dist"] = max_dist

        res = get_global_client().list_organization_events(params)
        return next(res)["data"][0:limit]
示例#6
0
def test_connection_error_retry():
    n = 0

    def callback(resp):
        nonlocal n
        n += 1
        if n == 1:
            raise ConnectionError("Connection reset by peer")
        return resp

    with responses.RequestsMock(response_callback=callback) as r:
        r.add(
            responses.GET,
            "https://localhost:8000/mobilize/v1/organizations/1/events?visibility=PUBLIC",
            body=json.dumps(LIST_EVENTS_RESPONSE),
            match_querystring=True,
        )
        res = mobilize_america.get_global_client().list_organization_events()
        page1 = next(res)
        assert n == 2
        assert {e["id"] for e in page1["data"]} == {172958, 175252, 179454}
示例#7
0
def test_list_events():
    responses.add(
        responses.GET,
        "https://localhost:8000/mobilize/v1/organizations/1/events?visibility=PUBLIC",
        body=json.dumps(LIST_EVENTS_RESPONSE),
        match_querystring=True,
    )
    responses.add(
        responses.GET,
        "https://localhost:8000/mobilize/v1/organizations/1/events?page=2&visibility=PUBLIC",
        body=json.dumps(LIST_EVENTS_RESPONSE_PAGE_2),
        match_querystring=True,
    )
    res = mobilize_america.get_global_client().list_organization_events()
    page1 = next(res)
    assert {e["id"] for e in page1["data"]} == {172958, 175252, 179454}
    assert len(responses.calls) == 1  # make sure pagination is lazy

    page2 = next(res)
    assert {e["id"] for e in page2["data"]} == {9620}
    with pytest.raises(StopIteration):
        next(res)
    assert len(responses.calls) == 2
示例#8
0
    def get(self, request, **kwargs):
        try:
            event_id = int(kwargs.get("id"))
        except ValueError:
            return Response(
                generate_error_for_code(
                    ErrorCodes.INVALID_EVENT_ID.name, {"detail": "Invalid Event ID"}
                ),
                status=status.HTTP_400_BAD_REQUEST,
            )
        event = MobilizeAmericaEvent.objects.filter(id=event_id, is_active=True)
        if event.exists():
            res = event.first().raw
        else:
            try:
                # get the response from mobilize america if it's not in our DB
                res = get_global_client().get_organization_event(event_id)["data"]
            except MobilizeAmericaAPIException as e:
                error_response, status_code = get_error_code_and_status(e.response)
                return Response(error_response, status=status_code)

        # The frontend is responsible for removing the full timeslots for switchboard/embedded shifter
        sanitized_res = mobilize_america_helpers.sanitize_event_payload(res)
        return Response(sanitized_res, status=status.HTTP_200_OK)