当前位置: 首页>>代码示例>>Python>>正文


Python utils.dict_to_struct函数代码示例

本文整理汇总了Python中relate.utils.dict_to_struct函数的典型用法代码示例。如果您正苦于以下问题:Python dict_to_struct函数的具体用法?Python dict_to_struct怎么用?Python dict_to_struct使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了dict_to_struct函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_flow_desc_access_rule_has_change_answer_perm

 def test_flow_desc_access_rule_has_change_answer_perm(self):
     flow_desc_dict = self.get_hacked_flow_desc(as_dict=True)
     rules = flow_desc_dict["rules"]
     rules.access = [dict_to_struct(
         {"permissions": ["submit_answer", "change_answer"]})]
     flow_desc = dict_to_struct(flow_desc_dict)
     self.assertTrue(analytics.is_flow_multiple_submit(flow_desc))
开发者ID:inducer,项目名称:relate,代码行数:7,代码来源:test_analytics.py

示例2: get_yaml_from_repo_side_effect

def get_yaml_from_repo_side_effect(repo, full_name, commit_sha, cached=True):
    if full_name == events_file:
        return dict_to_struct(
            {"event_kinds": dict_to_struct({
                "lecture": dict_to_struct({
                    "title": "Lecture {nr}",
                    "color": "blue"
                })}),
                "events": dict_to_struct({
                    "lecture 1": dict_to_struct({
                        "title": "l1"})
                })})
    else:
        return get_yaml_from_repo(repo, full_name, commit_sha, cached)
开发者ID:inducer,项目名称:relate,代码行数:14,代码来源:test_validate_course_content.py

示例3: test_parse_matcher_instance_is_struct_no_type_error

 def test_parse_matcher_instance_is_struct_no_type_error(self):
     s = dict_to_struct(
         {"value": "20.1"})
     with self.assertRaises(ValidationError) as cm:
         parse_matcher(None, "some where", s)
     self.assertIn("some where: matcher must supply 'type'",
                   str(cm.exception))
开发者ID:inducer,项目名称:relate,代码行数:7,代码来源:test_text.py

示例4: get_yaml_from_repo

def get_yaml_from_repo(repo, full_name, commit_sha, cached=True):
    """Return decoded, struct-ified YAML data structure from
    the given file in *repo* at *commit_sha*.

    See :class:`relate.utils.Struct` for more on
    struct-ification.
    """

    if cached:
        cache_key = "%%%2".join((repo.controldir(), full_name, commit_sha))

        import django.core.cache as cache

        def_cache = cache.caches["default"]
        result = def_cache.get(cache_key)
        if result is not None:
            return result

    result = dict_to_struct(
        load_yaml(expand_yaml_macros(repo, commit_sha, get_repo_blob(repo, full_name, commit_sha).data))
    )

    if cached:
        def_cache.add(cache_key, result, None)

    return result
开发者ID:gboone,项目名称:relate,代码行数:26,代码来源:content.py

示例5: get_flow_rules

def get_flow_rules(flow_desc, kind, participation, flow_id, now_datetime,
        consider_exceptions=True, default_rules_desc=[]):
    if (not hasattr(flow_desc, "rules")
            or not hasattr(flow_desc.rules, kind)):
        rules = default_rules_desc[:]
    else:
        rules = getattr(flow_desc.rules, kind)[:]

    from course.models import FlowRuleException
    if consider_exceptions:
        for exc in (
                FlowRuleException.objects
                .filter(
                    participation=participation,
                    active=True,
                    kind=kind,
                    flow_id=flow_id)
                # rules created first will get inserted first, and show up last
                .order_by("creation_time")):

            if exc.expiration is not None and now_datetime > exc.expiration:
                continue

            from relate.utils import dict_to_struct
            rules.insert(0, dict_to_struct(exc.rule))

    return rules
开发者ID:lukeolson,项目名称:relate,代码行数:27,代码来源:utils.py

示例6: test_choice_not_stringifiable

    def test_choice_not_stringifiable(self):
        expected_page_error = (
            "choice 10: unable to convert to string")

        class BadChoice(object):
            def __str__(self):
                raise Exception

        from relate.utils import dict_to_struct
        fake_page_desc = dict_to_struct(
            {'type': 'SurveyChoiceQuestion', 'id': 'age_group_with_comment',
             'answer_comment': 'this is a survey question',
             'prompt': '\n# Age\n\nHow old are you?\n',
             'choices': [
                 '0-10 years', '11-20 years', '21-30 years', '31-40 years',
                 '41-50 years', '51-60 years', '61-70 years', '71-80 years',
                 '81-90 years', BadChoice()],
             '_field_names': ['type', 'id', 'answer_comment',
                              'prompt', 'choices']}
        )

        with mock.patch("relate.utils.dict_to_struct") as mock_dict_to_struct:
            mock_dict_to_struct.return_value = fake_page_desc

            markdown = SURVEY_CHOICE_QUESTION_MARKDOWN

            resp = (
                self.get_page_sandbox_preview_response(markdown))
            self.assertEqual(resp.status_code, 200)
            self.assertSandboxNotHasValidPage(resp)
            self.assertResponseContextContains(resp, PAGE_ERRORS,
                                               expected_page_error)
开发者ID:inducer,项目名称:relate,代码行数:32,代码来源:test_choice.py

示例7: validate

    def validate(self, new_page_source):
        from relate.utils import dict_to_struct
        import yaml

        try:
            page_desc = dict_to_struct(yaml.safe_load(new_page_source))

            from course.validation import (
                    validate_flow_page, ValidationContext)
            vctx = ValidationContext(
                    # FIXME
                    repo=None,
                    commit_sha=None)

            validate_flow_page(vctx, "submitted page", page_desc)

            if page_desc.type != self.validator_desc.page_type:
                raise ValidationError(ugettext("page must be of type '%s'")
                        % self.validator_desc.page_type)

        except Exception:
            tp, e, _ = sys.exc_info()

            raise forms.ValidationError("%(err_type)s: %(err_str)s"
                    % {"err_type": tp.__name__, "err_str": str(e)})
开发者ID:ishitatsuyuki,项目名称:relate,代码行数:25,代码来源:text.py

示例8: check_attributes_yml

def check_attributes_yml(vctx, repo, path, tree):
    try:
        _, attr_blob_sha = tree[".attributes.yml"]
    except KeyError:
        # no .attributes.yml here
        pass
    else:
        from relate.utils import dict_to_struct
        from yaml import load as load_yaml

        att_yml = dict_to_struct(load_yaml(repo[attr_blob_sha].data))

        loc = path + "/" + ".attributes.yml"
        validate_struct(
                vctx, loc, att_yml,
                required_attrs=[],
                allowed_attrs=[
                    ("public", list),
                ])

        if hasattr(att_yml, "public"):
            for i, l in enumerate(att_yml.public):
                if not isinstance(l, (str, unicode)):
                    raise ValidationError(
                            "%s: entry %d in 'public' is not a string"
                            % (loc, i+1))

    import stat
    for entry in tree.items():
        if stat.S_ISDIR(entry.mode):
            _, blob_sha = tree[entry.path]
            subtree = repo[blob_sha]
            check_attributes_yml(vctx, repo, path+"/"+entry.path, subtree)
开发者ID:beesor,项目名称:relate,代码行数:33,代码来源:validation.py

示例9: check_attributes_yml

def check_attributes_yml(vctx, repo, path, tree):
    try:
        _, attr_blob_sha = tree[".attributes.yml"]
    except KeyError:
        # no .attributes.yml here
        pass
    else:
        from relate.utils import dict_to_struct
        from yaml import load as load_yaml

        att_yml = dict_to_struct(load_yaml(repo[attr_blob_sha].data))

        loc = path + "/" + ".attributes.yml"
        validate_struct(vctx, loc, att_yml, required_attrs=[], allowed_attrs=[("public", list), ("in_exam", list)])

        for access_kind in ["public", "in_exam"]:
            if hasattr(att_yml, access_kind):
                for i, l in enumerate(att_yml.public):
                    if not isinstance(l, six.string_types):
                        raise ValidationError("%s: entry %d in '%s' is not a string" % (loc, i + 1, access_kind))

    import stat

    for entry in tree.items():
        if stat.S_ISDIR(entry.mode):
            _, blob_sha = tree[entry.path]
            subtree = repo[blob_sha]
            check_attributes_yml(vctx, repo, path + "/" + entry.path.decode("utf-8"), subtree)
开发者ID:simudream,项目名称:relate,代码行数:28,代码来源:validation.py

示例10: get_yaml_from_repo

def get_yaml_from_repo(repo, full_name, commit_sha, cached=True):
    """Return decoded, struct-ified YAML data structure from
    the given file in *repo* at *commit_sha*.

    See :class:`relate.utils.Struct` for more on
    struct-ification.
    """

    if cached:
        from six.moves.urllib.parse import quote_plus
        cache_key = "%%%2".join(
                (quote_plus(repo.controldir()), quote_plus(full_name),
                    commit_sha.decode()))

        import django.core.cache as cache
        def_cache = cache.caches["default"]
        result = None
        # Memcache is apparently limited to 250 characters.
        if len(cache_key) < 240:
            result = def_cache.get(cache_key)
        if result is not None:
            return result

    expanded = expand_yaml_macros(
            repo, commit_sha,
            get_repo_blob(repo, full_name, commit_sha).data)

    result = dict_to_struct(load_yaml(expanded))

    if cached:
        def_cache.add(cache_key, result, None)

    return result
开发者ID:akiyoko,项目名称:relate,代码行数:33,代码来源:content.py

示例11: test_parse_matcher_instance_is_struct

 def test_parse_matcher_instance_is_struct(self):
     s = dict_to_struct(
         {"type": "float",
          "value": "20.1",
          })
     result = parse_matcher(None, "", s)
     self.assertTrue(isinstance(result, FloatMatcher))
     self.assertEqual(result.correct_answer_text(), "20.1")
开发者ID:inducer,项目名称:relate,代码行数:8,代码来源:test_text.py

示例12: test_float_matcher_value_zero_rtol_zero_error

 def test_float_matcher_value_zero_rtol_zero_error(self):
     expected_error_msg = "'rtol' not allowed when 'value' is zero"
     with self.assertRaises(ValidationError) as cm:
         FloatMatcher(None, "",
                      dict_to_struct(
                          {"type": "float",
                           "value": "0",
                           "rtol": "0"}))
     self.assertIn(expected_error_msg, str(cm.exception))
开发者ID:inducer,项目名称:relate,代码行数:9,代码来源:test_text.py

示例13: test_float_matcher_neither_atol_nor_rtol_present_warning

 def test_float_matcher_neither_atol_nor_rtol_present_warning(self):
     mock_vctx = mock.MagicMock()
     expected_warning = ("Float match should have either rtol or atol--"
                         "otherwise it will match any number")
     FloatMatcher(mock_vctx, "some where",
                  dict_to_struct(
                      {"type": "float",
                       "value": "1"}))
     self.assertIn(expected_warning, mock_vctx.add_warning.call_args[0])
开发者ID:inducer,项目名称:relate,代码行数:9,代码来源:test_text.py

示例14: test_float_matcher_atol_error

 def test_float_matcher_atol_error(self):
     expected_error_msg = "'atol' does not provide a valid float literal"
     with self.assertRaises(ValidationError) as cm:
         FloatMatcher(None, "",
                      dict_to_struct(
                          {"type": "float",
                           "value": "1",
                           "atol": "abcd"}))
     self.assertIn(expected_error_msg, str(cm.exception))
开发者ID:inducer,项目名称:relate,代码行数:9,代码来源:test_text.py

示例15: test_float_matcher_value_zero_atol_not_present_warning

    def test_float_matcher_value_zero_atol_not_present_warning(self):
        mock_vctx = mock.MagicMock()
        expected_warning = ("Float match for 'value' zero should have "
                            "atol--otherwise it will match any number")
        FloatMatcher(mock_vctx, "some where",
                     dict_to_struct(
                         {"type": "float",
                          "value": "0"}))

        self.assertIn(expected_warning, mock_vctx.add_warning.call_args[0])
开发者ID:inducer,项目名称:relate,代码行数:10,代码来源:test_text.py


注:本文中的relate.utils.dict_to_struct函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。