示例#1
0
def test_process_env_install_from_source(
    tmpdir: py.path.local,
    tmpvenv_active: Tuple[py.path.local, py.path.local],
    modules_v2_dir: str,
    editable: bool,
) -> None:
    """
    Install a package from source into the process_env. Make sure the editable option actually results in an editable install.
    """
    venv_dir, python_path = tmpvenv_active
    package_name: str = "inmanta-module-minimalv2module"
    project_dir: str = os.path.join(modules_v2_dir, "minimalv2module")
    assert package_name not in env.process_env.get_installed_packages()
    env.process_env.install_from_source(
        [env.LocalPackagePath(path=project_dir, editable=editable)])
    assert package_name in env.process_env.get_installed_packages()
    if editable:
        assert any(package["name"] == package_name
                   for package in pydantic.parse_raw_as(
                       List[Dict[str, str]],
                       subprocess.check_output([
                           python_path, "-m", "pip", "list", "--editable",
                           "--format", "json"
                       ]).decode(),
                   ))
示例#2
0
    async def get(self):
        """Получить.

        :return: list[BaseModel]
        """
        logger.info('Searching cached...')
        cache = await self._cache_connection.get(str(hash(self._origin)))
        if cache:
            logger.info('Cached data founded')
            return parse_raw_as(list[self._model_to_parse],
                                cache)  # type: ignore

        logger.info('Cached data not founded')
        origin_get_result = await self._origin.get()
        logger.info('Setting data to cache')
        pagination_elements = [
            pagination_element.dict()
            for pagination_element in origin_get_result
        ]
        await self._cache_connection.set(
            str(hash(self._origin)),
            json.dumps(pagination_elements),
            ex=60 * 60,
        )
        logger.info('Data setted to cache')
        return origin_get_result
示例#3
0
 async def get_content_preview(self,
                               content_preview_link: str) -> ContentPreview:
     """
     Returns the results from the specified content preview link.
     """
     result = await self._get(content_preview_link)
     return parse_raw_as(ContentPreview, result)
示例#4
0
 async def get_file(self, mod_id: int, file_id: int) -> File:
     """
     Returns the specified file for the specified mod.
     """
     result = await self._get(
         f"{self.BASE_URL}/games/{self.game_domain_name}/mods/{mod_id}/files/{file_id}.json"
     )
     return parse_raw_as(File, result)
示例#5
0
 async def get_mod(self, mod_id: int) -> Mod:
     """
     Returns a specified mod. Cached for 5 minutes.
     """
     result = await self._get(
         f"{self.BASE_URL}/games/{self.game_domain_name}/mods/{mod_id}.json"
     )
     return parse_raw_as(Mod, result)
示例#6
0
 async def get_mod_changelogs(self, mod_id: int) -> dict[str, list[str]]:
     """
     Returns a list of changelogs for the specified mod.
     """
     result = await self._get(
         f"{self.BASE_URL}/games/{self.game_domain_name}/mods/{mod_id}/changelogs.json"
     )
     return parse_raw_as(dict[str, list[str]], result)
示例#7
0
 async def get_trending_mods(self) -> list[Mod]:
     """
     Returns 10 trending mods.
     """
     result = await self._get(
         f"{self.BASE_URL}/games/{self.game_domain_name}/mods/trending.json"
     )
     return parse_raw_as(list[Mod], result)
示例#8
0
文件: conftest.py 项目: jbouwh/core
def mock_lametric_cloud_config_flow() -> Generator[MagicMock, None, None]:
    """Return a mocked LaMetric Cloud client."""
    with patch("homeassistant.components.lametric.config_flow.LaMetricCloud",
               autospec=True) as lametric_mock:
        lametric = lametric_mock.return_value
        lametric.devices.return_value = parse_raw_as(
            list[CloudDevice], load_fixture("cloud_devices.json", DOMAIN))
        yield lametric
示例#9
0
 async def get_latest_updated_mods(self) -> list[Mod]:
     """
     Returns the 10 latest updated mods.
     """
     result = await self._get(
         f"{self.BASE_URL}/games/{self.game_domain_name}/mods/latest_updated.json"
     )
     return parse_raw_as(list[Mod], result)
示例#10
0
def get_boards(member: str,
               query: Optional[Dict[str, str]] = DEFAULT_QUERY) -> List[Board]:
    """
    https://developer.atlassian.com/cloud/trello/rest/api-group-members/#api-members-id-boards-get
    """
    url = f"https://api.trello.com/1/members/{ member }/boards"
    headers = {"Accept": "application/json"}
    response = requests.request("GET", url, headers=headers, params=query)
    return parse_raw_as(List[Board], response.text)
示例#11
0
 async def get_md5_search(self, md5_hash: str) -> list[tuple[Mod, File]]:
     """
     Returns a list of mod files for the given MD5 file hash.
     """
     result = await self._get(
         f"{self.BASE_URL}/games/{self.game_domain_name}/mods/md5_search/{md5_hash}.json"
     )
     parsed = parse_raw_as(list[SearchResult], result)
     return [(p.mod, p.file_details) for p in parsed]
示例#12
0
 async def get_download_links(self, mod_id: int,
                              file_id: int) -> list[DownloadLink]:
     """
     Returns a generated download link for the specified mod file.
     """
     result = await self._get(
         f"{self.BASE_URL}/games/{self.game_domain_name}/mods/{mod_id}/files/{file_id}/download_link.json"
     )
     return parse_raw_as(list[DownloadLink], result)
示例#13
0
 async def get_files_and_updates(
         self, mod_id: int) -> tuple[list[File], list[FileUpdate]]:
     """
     Returns a list of files for the specified mod.
     """
     result = await self._get(
         f"{self.BASE_URL}/games/{self.game_domain_name}/mods/{mod_id}/files.json"
     )
     parsed = parse_raw_as(FilesResult, result)
     return parsed.files, parsed.file_updates
示例#14
0
 async def get_mod_updates(self, period: str) -> list[ModUpdate]:
     """
     Returns a list of mods that have been updated in a given period, with timestamps of their last update.
     Cached for 5 minutes.
     The only accepted periods are '1d', '1w' and '1m' (1 day, 1 week and 1 month).
     """
     json: _JsonDict = {"period": period}
     result = await self._get(
         f"{self.BASE_URL}/games/{self.game_domain_name}/mods/updated.json",
         json=json)
     return parse_raw_as(list[ModUpdate], result)
示例#15
0
def get_cards(board: Union[str, Board],
              query: Optional[Dict[str, str]] = DEFAULT_QUERY) -> List[Card]:
    """
    https://developer.atlassian.com/cloud/trello/rest/api-group-boards/#api-boards-id-cards-get
    """
    if isinstance(board, Board):
        board = board.id

    url = f"https://api.trello.com/1/boards/{ board }/cards"
    response = requests.request("GET", url, params=query)
    return parse_raw_as(List[Card], response.text)
def update_employer_job_answers(event: dict, context: LambdaContext) -> dict:
    try:
        if 'pathParameters' not in event or not event['pathParameters'] \
                or 'employer_id' not in event['pathParameters'] or 'job_id' not in event['pathParameters'] \
                or 'body' not in event or not event['body']:
            return {
                'statusCode': HTTPStatus.BAD_REQUEST,
                'headers': EmployerConstants.HEADERS,
                'body': "Missing employer job body/path params to create"
            }
        employer_answers: List[Answer] = parse_raw_as(List[Answer],
                                                      event['body'])
        employer_id = event['pathParameters']['employer_id']
        job_id = event['pathParameters']['job_id']
        dynamo_resource = boto3.resource("dynamodb")
        jobs_table = dynamo_resource.Table(
            get_env_or_raise(EmployerConstants.JOBS_TABLE_NAME))

        stored_job: EmployerJob = EmployerJob.parse_obj(
            jobs_table.get_item(Key={
                'job_id': job_id
            }).get('Item', {}))
        if stored_job.employer_id != employer_id:
            return {
                'statusCode': HTTPStatus.BAD_REQUEST,
                'headers': EmployerConstants.HEADERS,
                'body': "Given employer id does not match job id"
            }
        stored_job.answers = employer_answers
        jobs_table.update_item(Key={"job_id": job_id},
                               UpdateExpression="set answers=:a",
                               ExpressionAttributeValues={
                                   ":a":
                                   [a.dict() for a in stored_job.answers],
                               },
                               ReturnValues="UPDATED_NEW")
        return {
            'statusCode': HTTPStatus.CREATED,
            'headers': EmployerConstants.HEADERS,
            'body': stored_job.json(exclude_none=True)
        }
    except (ValidationError, TypeError) as err:
        return {
            'statusCode': HTTPStatus.BAD_REQUEST,
            'headers': EmployerConstants.HEADERS,
            'body': str(err)
        }
    except Exception as err:
        return {
            'statusCode': HTTPStatus.INTERNAL_SERVER_ERROR,
            'headers': EmployerConstants.HEADERS,
            'body': str(err)
        }
示例#17
0
 async def set_tracked(self, mod_id: int, tracked: bool) -> Message:
     """Track or untrack a mod."""
     json: _JsonDict = {
         "domain_name": self.game_domain_name,
         "mod_id": mod_id
     }
     if tracked:
         result = await self._post(
             f"{self.BASE_URL}/user/tracked_mods.json", json=json)
     else:
         result = await self._delete(
             f"{self.BASE_URL}/user/tracked_mods.json", json=json)
     return parse_raw_as(Message, result)
示例#18
0
    def __call__(self, input: Any, **kwargs: Any) -> Any:

        input_obj = input

        if isinstance(input, str):
            # Allow json input
            input_obj = parse_raw_as(self.input_type, input)

        if isinstance(input, dict):
            # Allow dict input
            input_obj = parse_obj_as(self.input_type, input)

        return self.function(input_obj, **kwargs)
示例#19
0
 async def set_endorsed(self, mod_id: int, version: str,
                        endorsed: bool) -> Status:
     """Endorse or unendorse a mod."""
     json: _JsonDict = {"version": version}
     if endorsed:
         result = await self._post(
             f"{self.BASE_URL}/games/{self.game_domain_name}/mods/{mod_id}/endorse.json",
             json=json,
         )
     else:
         result = await self._post(
             f"{self.BASE_URL}/games/{self.game_domain_name}/mods/{mod_id}/abstain.json",
             json=json,
         )
     return parse_raw_as(Status, result)
示例#20
0
async def actions(request: Request):
    form = await request.form()
    payload: Payload = parse_raw_as(Payload, form['payload'])
    if payload.is_view_submission:
        # モーダルに入力した内容を送信するイベント
        return RedirectResponse('./view_submission/')
    if payload.is_shortcut:
        # ショートカット(「emojiを追加」「emojiを編集」)を選択したイベント
        return RedirectResponse('./shortcuts/')
    if payload.is_block_actions:
        if payload.container:
            if payload.container.is_message:
                # 「読んだ」ボタンを押したイベント
                return RedirectResponse('./message/')
    return Response()
示例#21
0
def get_checklists(
        card: Union[str, Card],
        query: Optional[Dict[str, str]] = DEFAULT_QUERY) -> List[CheckList]:
    """
    https://developer.atlassian.com/cloud/trello/rest/api-group-cards/#api-cards-id-checklists-get
    """
    if isinstance(card, Card):
        card = card.id
    url = f"https://api.trello.com/1/cards/{ card }/checklists"

    response = requests.request("GET", url, params=query)
    try:
        return parse_raw_as(List[CheckList], response.text)
    except Exception as exception:
        print(response.text)
示例#22
0
def cli() -> None:
    with open("senderconfig.json") as fh:
        senderconfig = pydantic.parse_raw_as(SenderConfigFile, fh.read())

    argparser = ArgumentParser()
    argparser.add_argument("campaign",
                           help="The name of the data file + template to send")
    argparser.add_argument("--sender",
                           choices=senderconfig.keys(),
                           help="Name of the senderconfig to use")
    argparser.add_argument(
        "--no-confirmations",
        action="store_false",
        default=True,
        dest="confirmations",
        help="I exactly know what I'm doing, just send everything immediately.",
    )
    args = argparser.parse_args()
    sender_name = args.sender
    if sender_name is None:
        print("Please select a sender configuration:")
        print()
        for name, data in senderconfig.items():
            print("  [{}]: {}".format(
                name, ", ".join(f"{k}: '{v}'"
                                for k, v in data.headers.items())) +
                  (f"; mock send to {data.override_recipient}" if data.
                   override_recipient is not None else ""))
        print()
        sender_name = input("Your selection: ")
        if sender_name not in senderconfig.keys():
            print("Invalid selection", file=sys.stderr)
            sys.exit(1)
        print()

    sys.exit(main(args.campaign, senderconfig[sender_name],
                  args.confirmations))
示例#23
0
    def __init__(self):
        self.exit = 0
        try:
            self.settings = Settings()
        except ValidationError as e:
            log(f'error loading Settings:\n{e}')
            self.exit = 1
            return

        contents = self.settings.github_event_path.read_text()
        event = parse_raw_as(Union[IssueEvent, PullRequestEvent], contents)
        force_assign_author = False

        if hasattr(event, 'issue'):
            event = cast(IssueEvent, event)
            if event.issue.pull_request is None:
                log('action only applies to pull requests, not issues')
                return

            comment = event.comment
            pr = event.issue
            event_type = 'comment'
        else:
            event = cast(PullRequestEvent, event)
            comment = event.review
            if comment.body is None:
                log('review has no body, stopping')
                return
            pr = event.pull_request
            force_assign_author = event.review.state == 'changes_requested'
            event_type = 'review'

        self.commenter = comment.user.login
        body = comment.body.lower()
        number = pr.number
        self.author = pr.user.login
        # hack until https://github.com/samuelcolvin/pydantic/issues/1458 gets fixed
        self.reviewers = [
            r.strip(' ') for r in self.settings.reviewers.split(',')
            if r.strip(' ')
        ]

        g = Github(self.settings.token.get_secret_value())
        repo = g.get_repo(self.settings.github_repository)
        self.pr = repo.get_pull(number)
        self.commenter_is_reviewer = self.commenter in self.reviewers
        self.commenter_is_author = self.author == self.commenter

        log(f'{self.commenter} ({event_type}): {body!r}')
        if self.settings.request_review_trigger in body:
            success, msg = self.request_review()
        elif self.settings.request_update_trigger in body or force_assign_author:
            success, msg = self.assign_author()
        else:
            success = False
            msg = (
                f'neither {self.settings.request_update_trigger!r} nor {self.settings.request_review_trigger!r} '
                f'found in comment body, not proceeding')

        if success:
            if event_type == 'comment':
                self.pr.get_issue_comment(comment.id).create_reaction('+1')
            log(f'success: {msg}')
        else:
            log(f'warning: {msg}')
示例#24
0
 async def get_game(self) -> Game:
     """Returns the specified game."""
     result = await self._get(
         f"{self.BASE_URL}/games/{self.game_domain_name}.json")
     return parse_raw_as(Game, result)
示例#25
0
 async def get_user(self) -> User:
     """Returns the current user."""
     result = await self._get(f"{self.BASE_URL}/users/validate.json")
     return parse_raw_as(User, result)
示例#26
0
 async def get_tracked_mods(self) -> list[TrackedMod]:
     """Returns all the mods being tracked by the current user."""
     result = await self._get(f"{self.BASE_URL}/user/tracked_mods.json")
     return parse_raw_as(list[TrackedMod], result)
示例#27
0
def json_string_to_pydantic(
    serialized_value: str,
    destination_type: Type[PydanticModel],
) -> PydanticModel:
    """Convert a JSON representation of a Pydantic model into model instance."""
    return pydantic.parse_raw_as(destination_type, serialized_value)
示例#28
0
def parse_configuration(content: str) -> list[Configuration]:
    config_lst = parse_raw_as(List[Configuration], content)
    if len(config_lst) == 0:
        sys.exit("Leere Konfigurationsdateien sind nicht erlaubt.\n")
    return config_lst
示例#29
0
 async def get_endorsements(self) -> list[Endorsement]:
     """Returns a list of all endorsements for the current user."""
     result = await self._get(f"{self.BASE_URL}/user/endorsements.json")
     return parse_raw_as(list[Endorsement], result)
示例#30
0
 async def get_colour_schemes(self) -> list[ColourScheme]:
     """
     Returns list of all colour schemes, including the primary, secondary and 'darker' colours.
     """
     result = await self._get(f"{self.BASE_URL}/colourschemes.json")
     return parse_raw_as(list[ColourScheme], result)