Example #1
0
def _assessment_types_of_class_for_state(
    assessment_class: StateAssessmentClass, state_code: str
) -> Optional[List[StateAssessmentType]]:
    """Returns the StateAssessmentType values that should be included in metric output for the given |assessment_class|
    and |state_code|."""
    types_for_class = _ASSESSMENT_TYPES_TO_INCLUDE_FOR_CLASS.get(assessment_class)

    if types_for_class:
        if environment.in_test() and state_code == StateCode.US_XX.value:
            # In testing, return all supported assessment types for this
            # assessment_class
            return [
                assessment_type
                for state_list in types_for_class.values()
                for assessment_type in state_list
            ]

        assessment_types_to_include = types_for_class.get(state_code)

        if not assessment_types_to_include:
            raise ValueError(
                f"Unsupported state_code {state_code} in _ASSESSMENT_TYPES_TO_INCLUDE_FOR_CLASS."
            )

        return assessment_types_to_include

    return None
    def database_version(
        # TODO(#7984): Remove the state_code arg once all states have been migrated to
        #   multi-DB.
        self,
        system_level: SystemLevel,
        state_code: Optional[StateCode],
    ) -> SQLAlchemyStateDatabaseVersion:
        """Return the database version for this instance."""
        self.check_is_valid_system_level(system_level)

        if system_level == SystemLevel.COUNTY:
            # County direct ingest writes to single, multi-tenant database
            return SQLAlchemyStateDatabaseVersion.LEGACY

        if system_level == SystemLevel.STATE:
            if not state_code:
                raise ValueError("Found null state_code for STATE schema.")
            if self == self.SECONDARY:
                return SQLAlchemyStateDatabaseVersion.SECONDARY
            if self == self.PRIMARY:
                # TODO(#7984): Switch this to SQLAlchemyStateDatabaseVersion.PRIMARY
                #  once all states have been migrated to multi-DB.
                if metadata.project_id(
                ) not in STATE_TO_PRIMARY_DATABASE_VERSION:
                    if not environment.in_test():
                        raise ValueError(
                            f"Unexpected project id {metadata.project_id()}")
                    return SQLAlchemyStateDatabaseVersion.LEGACY

                return STATE_TO_PRIMARY_DATABASE_VERSION[
                    metadata.project_id()][state_code]

        raise ValueError(
            f"Unexpected combination of [{system_level}] and instance type [{self}]"
        )
Example #3
0
def stats():
    global _stats
    if not _stats:
        new_stats = stats_module.Stats()
        if environment.in_gae() and not environment.in_test():
            exporter = stackdriver.new_stats_exporter(
                stackdriver.Options(project_id=metadata.project_id(), ))
            new_stats.view_manager.register_exporter(exporter)
        _stats = new_stats
    return _stats
Example #4
0
def read_pdf(location: str, filename: str, **kwargs):
    if environment.in_test():
        return tabula.read_pdf(filename, **kwargs)

    client_id = _CLIENT_ID[project_id()]
    url = f'https://read-pdf-dot-{project_id()}.appspot.com/read_pdf'

    response = make_iap_request(url,
                                client_id,
                                method='POST',
                                params={
                                    'location': location,
                                    'filename': os.path.basename(filename)
                                },
                                json=kwargs)
    response.raise_for_status()
    return pickle.loads(response.content)
Example #5
0
def _get_metadata(url: str) -> Optional[str]:
    if url in _metadata_cache:
        return _metadata_cache[url]

    if not allow_local_metadata_call:
        if environment.in_test() or not environment.in_gcp():
            raise RuntimeError(
                "May not be called from test, should this have a local override?"
            )

    try:
        r = requests.get(BASE_METADATA_URL + url, headers=HEADERS, timeout=TIMEOUT)
        r.raise_for_status()
        _metadata_cache[url] = r.text
        return r.text
    except Exception as e:
        logging.error("Failed to fetch metadata [%s]: [%s]", url, e)
        return None
Example #6
0
def __getattr__(name: str) -> Any:
    if name == "StateCode":
        if environment.in_test():
            return _FakeStateCode
        return _RealStateCode
    raise AttributeError(f"states module has no attribute '{name}")
Example #7
0
auth0_configuration = get_local_secret("case_triage_auth0")

if not auth0_configuration:
    raise ValueError("Missing Case Triage Auth0 configuration secret")

authorization_store = AuthorizationStore()
authorization_config = Auth0Config(json.loads(auth0_configuration))
requires_authorization = build_auth0_authorization_decorator(
    authorization_config, on_successful_authorization)

store_refresh = RepeatedTimer(15 * 60,
                              authorization_store.refresh,
                              run_immediately=True)

if not in_test():
    store_refresh.start()


# Security headers
@app.after_request
def set_headers(response: Response) -> Response:
    if not in_development():
        response.headers[
            "Strict-Transport-Security"] = "max-age=63072000"  # max age of 2 years
    response.headers["Content-Security-Policy"] = "frame-ancestors 'none'"
    response.headers["X-Frame-Options"] = "DENY"
    return response


# Routes & Blueprints
Example #8
0
def test_test_in_test():
    assert environment.in_test()
Example #9
0
def register_views(views):
    if environment.in_gae() and not environment.in_test():
        for view in views:
            stats().view_manager.register_view(view)
Example #10
0
class StateCode(enum.Enum):
    """Code for every state in the US"""

    US_AK = "US_AK"
    US_AL = "US_AL"
    US_AR = "US_AR"
    US_AZ = "US_AZ"
    US_CA = "US_CA"
    US_CO = "US_CO"
    US_CT = "US_CT"
    US_DE = "US_DE"
    US_FL = "US_FL"
    US_GA = "US_GA"
    US_HI = "US_HI"
    US_IA = "US_IA"
    US_ID = "US_ID"
    US_IL = "US_IL"
    US_IN = "US_IN"
    US_KS = "US_KS"
    US_KY = "US_KY"
    US_LA = "US_LA"
    US_MA = "US_MA"
    US_MD = "US_MD"
    US_ME = "US_ME"
    US_MI = "US_MI"
    US_MN = "US_MN"
    US_MO = "US_MO"
    US_MS = "US_MS"
    US_MT = "US_MT"
    US_NC = "US_NC"
    US_ND = "US_ND"
    US_NE = "US_NE"
    US_NH = "US_NH"
    US_NJ = "US_NJ"
    US_NM = "US_NM"
    US_NV = "US_NV"
    US_NY = "US_NY"
    US_OH = "US_OH"
    US_OK = "US_OK"
    US_OR = "US_OR"
    US_PA = "US_PA"
    US_RI = "US_RI"
    US_SC = "US_SC"
    US_SD = "US_SD"
    US_TN = "US_TN"
    US_TX = "US_TX"
    US_UT = "US_UT"
    US_VA = "US_VA"
    US_VT = "US_VT"
    US_WA = "US_WA"
    US_WI = "US_WI"
    US_WV = "US_WV"
    US_WY = "US_WY"

    if environment.in_test():
        US_XX = TEST_STATE_CODE

    def get_state(self) -> us.states.State:
        return self._state_info_map()[self.value]

    @classmethod
    def _state_info_map(cls) -> Dict[str, us.states.State]:
        info_map = {}
        for e in cls:
            state_abbrev = e.value[len("US_") :]
            if hasattr(us.states, state_abbrev):
                info_map[e.value] = getattr(us.states, state_abbrev)
            elif e.value in TEST_STATE_INFO:
                info_map[e.value] = TEST_STATE_INFO[e.value]
            else:
                raise ValueError(
                    f"Unexpected state code [{e.value}] has no state info."
                )

        return info_map

    @classmethod
    def is_valid(cls, state_code: str) -> bool:
        return cls.is_state_code(state_code)

    @classmethod
    def is_state_code(cls, state_code: str) -> bool:
        try:
            StateCode(state_code.upper())
            return True
        except ValueError as _:
            return False
Example #11
0
def test_test_in_test() -> None:
    assert environment.in_test()