Example #1
0
def test_loop_user_friendliness():
    template = Template(
        [Loop({
            'over': 'domain_names',
            'template': Var('item')
        })])
    ctx = Context(LOOP_TEST_CONTEXT)
    with pytest.raises(ValueError) as ei:
        template.render(ctx)
    assert 'did you mean' in str(ei.value)
Example #2
0
def test_format():
    template = Template.parse(
        '!Format "This tests formatting. {person.name!s} {chance:.0%} == {chance:.5f}"', 'yaml'
    )
    ctx = Context({'person': {'name': 'Pipimi'}, 'chance': .99})
    output = template.enrich(ctx)[0]
    assert output == 'This tests formatting. Pipimi 99% == 0.99000'
Example #3
0
def test_format_var():
    assert Template.parse('''
!Defaults
a: !Op [2, plus, 3]
---
!Format "five {a}"
    ''').enrich({}) == ['five 5']
Example #4
0
def test_urlencode_enrich_str():
    assert (Template.parse('''
!Defaults
bar: "foo+bar"
---
!URLEncode,Var bar
''').enrich({}) == ['foo%2Bbar'])
Example #5
0
def test_index_result_as():
    assert Template.parse('''
!Index
  over:
    - name: manifold
      score: 7.8
    - name: John
      score: 9.9
    - name: John
      score: 9.8
  as: flavour
  template:
    NAME: !Lookup flavour.name
    SCORE: !Lookup flavour.score
  result_as: result
  by: !Lookup result.NAME
  duplicates: ignore
    ''').enrich({}) == [{
        'manifold': {
            'NAME': 'manifold',
            'SCORE': 7.8
        },
        'John': {
            'NAME': 'John',
            'SCORE': 9.8
        }
    }]
Example #6
0
def test_multiple_include_defaults():
    filename = os.path.join(BASE_DIR, 'test_include_defaults.in.yml')
    template = Template.parse('''
        ab:
            !MultiInclude includes/multi-include-*.in.yml
        ''',
                              filename=filename)
    enrich = template.enrich({})
    assert enrich == [{
        'ab': [{
            'a': 1,
            'aa': 11,
            'aaa': 111
        }, {
            'b': 2,
            'bb': 22,
            'bbb': 222
        }, {
            'd': 4,
            'dd': 44,
            'ddd': 444
        }, {
            'e': 5,
            'ee': 55,
            'eee': 555
        }]
    }]
Example #7
0
def test_loop(examples_dir):
    with open('{examples_dir}/loop.yml'.format(examples_dir=examples_dir),
              'r') as inf:
        template = Template.parse(inf, 'yaml')
    ctx = Context(LOOP_TEST_CONTEXT)
    output = template.render(ctx)
    assert (output.strip() == '''
domains:
- apiVersion: v1
  kind: DomainName
  metadata:
    index: 0
    name: hernekeit.to
- apiVersion: v1
  kind: DomainName
  metadata:
    index: 1
    name: vii.na
- apiVersion: v1
  kind: DomainName
  metadata:
    index: 2
    name: teli.ne
- apiVersion: v1
  kind: DomainName
  metadata:
    index: 3
    name: johann.es
'''.strip())
Example #8
0
    def generate(self):
        appimage_builder_yml_template_path = os.path.realpath(
            os.path.join(os.path.dirname(__file__), 'templates',
                         'AppImageBuilder.yml.in'))
        with open(appimage_builder_yml_template_path, 'r') as filedata:
            appimage_builder_yml_template = Template.parse(filedata, 'yaml')

        appimage_builder_yml_ctx = Context({
            'app_info_id': self.app_info_id,
            'app_info_name': self.app_info_name,
            'app_info_icon': self.app_info_icon,
            'app_info_version': self.app_info_version,
            'app_info_exec': self.app_info_exec,
            'app_info_exec_args': self.app_info_exec_args,
            'runtime_generator': self.runtime_generator,
            'runtime_env': self.runtime_env,
            'apt_arch': self.apt_arch,
            'apt_sources': self.apt_sources,
            'apt_includes': self.apt_includes,
            'apt_excludes': self.apt_excludes,
            'files_excludes': self.files_excludes,
            'appimage_arch': self.appimage_arch,
        })

        rendered_yml = appimage_builder_yml_template.render(
            appimage_builder_yml_ctx)
        logging.info(rendered_yml)

        with open('AppImageBuilder.yml', 'w') as f:
            f.write(rendered_yml)

        self.logger.info("Recipe generation completed.")
        self.logger.info(
            "Please manually fill any blank field left before calling appimage-builder"
        )
Example #9
0
def test_op():
    template = Template.parse('''
!Op
  a: 1
  op: +
  b: 1
''', 'yaml')
    assert template.enrich({}) == [2]
Example #10
0
def test_previous_as():
    assert Template.parse('''
!Loop
  over: [1, 2, 3]
  as: item
  previous_as: previous_item
  template: [!Var previous_item, !Var item]
''').enrich({}) == [[[None, 1], [1, 2], [2, 3]]]
Example #11
0
def test_include_chained_defaults():
    filename = os.path.join(BASE_DIR, 'test_include_chained_defaults.in.yml')
    template = Template.parse('''
!Include includes/chained_defaults.in.yml
---
foo: !Var foo
''', filename=filename)
    assert template.enrich({}) == [{'foo': 5}]
Example #12
0
def test_consecutive_include_at_top_level():
    filename = os.path.join(BASE_DIR, 'test_consecutive_include_at_top_level.in.yml')
    template = Template.parse('''
!Include includes/good.in.yml
---
!Include includes/good.in.yml
''', filename=filename)
    assert template.enrich({}) == [{'foo': 5}, {'foo': 5}]
Example #13
0
def test_include_multi():
    filename = os.path.join(BASE_DIR, 'test_include_multi.in.yml')
    template = Template.parse('!Include includes/multi.in.yml', filename=filename)

    with pytest.raises(ValueError) as err:
        template.enrich({})

    assert 'single-document' in str(err.value)
Example #14
0
def test_urlencode_query():
    template = Template.parse("""
        !URLEncode
            query:
                foo: bar
""")

    assert template.enrich({}) == ['foo=bar']
Example #15
0
    def generate(self):
        template_file_name = "apt.yml.in" if self.apt_includes else "files.yml.in"

        appimage_builder_yml_template_path = os.path.join(
            os.path.dirname(__file__), "templates", template_file_name)

        with open(appimage_builder_yml_template_path, "r") as filedata:
            appimage_builder_yml_template = Template.parse(filedata, "yaml")

        appimage_builder_yml_ctx = Context({
            "app_info_id":
            self.app_info_id,
            "app_info_name":
            self.app_info_name,
            "app_info_icon":
            self.app_info_icon,
            "app_info_version":
            self.app_info_version,
            "app_info_exec":
            self.app_info_exec,
            "app_info_exec_args":
            self.app_info_exec_args,
            "runtime_generator":
            self.runtime_generator,
            "runtime_env":
            self.runtime_env,
            "apt_arch":
            self.apt_arch,
            "apt_sources":
            self.apt_sources,
            "apt_includes":
            self.apt_includes,
            "apt_excludes":
            self.apt_excludes,
            "files_includes":
            self.files_include,
            "files_excludes":
            self.files_exclude,
            "appimage_arch":
            self.appimage_arch,
            "appimage_update_information":
            self.appimage_update_information,
        })

        rendered_yml = appimage_builder_yml_template.render(
            appimage_builder_yml_ctx)
        logging.info(rendered_yml)

        with open("AppImageBuilder.yml", "w") as f:
            f.write(
                "# appimage-builder recipe see https://appimage-builder.readthedocs.io for details\n"
            )
            f.write(rendered_yml)

        self.logger.info("Recipe generation completed.")
        self.logger.info(
            "Please manually fill any blank field left before calling appimage-builder"
        )
Example #16
0
def test_typeop(tag, val, result):
    resolved = Template.parse("!%s,Lookup 'a'" % tag).enrich(
        Context({'a': val}))[0]
    assert resolved == result, '{tag}({val!r}) returned {resolved}, expected {result}'.format(
        tag=tag,
        val=val,
        resolved=resolved,
        result=result,
    )
Example #17
0
def test_compose_syntax(format):
    source = {
        'yaml': '!Base64,Format "hello {thing}"',
        'json': '{"!Base64,Format": "hello {thing}"}',
    }
    template = Template.parse(source[format], format)
    ctx = Context(CONTEXT)
    output = template.enrich(ctx)[0]
    assert base64.b64decode(output).decode() == 'hello world'
Example #18
0
def test_hash_variable(h):
    algo, expected = h

    VARIABLES = """
    helloVar: Hello
    """

    assert Template.parse(f'!{algo},Var helloVar').enrich(
        Context(VARIABLES)) == [expected]
Example #19
0
def test_loop_index_start():
    template = Template.parse('''
!Loop
  over: [1, 2, 3]
  index_start: 5
  index_as: index
  template: !Var index
''')
    assert template.enrich({}) == [[5, 6, 7]]
Example #20
0
def test_urlencode_url():
    template = Template.parse("""
        !URLEncode
            url: "https://example.com/?foo=x"
            query:
                bar: xyzzy
""")

    assert template.enrich({}) == ['https://example.com/?foo=x&bar=xyzzy']
Example #21
0
def test_urlencode_enrich_query():
    template = Template.parse("""
!Defaults
bar: bar
---
!URLEncode
    query:
        foo: !Var bar
""")
    assert template.enrich({}) == ['foo=bar']
Example #22
0
def test_filter_op():
    template = Template.parse('''
!Filter
  test: !Op
    a: !Var item
    op: gt
    b: 4
  over: [1, 7, 2, 5]
''')
    assert template.enrich({}) == [[7, 5]]
Example #23
0
def test_debug(capsys):
    assert Template.parse('''
!Defaults
a: 5
---
b: !Debug,Var a
''').enrich({})[0] == {
        'b': 5
    }
    captured = capsys.readouterr()
    assert captured.err == '5\n'
Example #24
0
def test_urlencode_enrich_url_string():
    template = Template.parse("""
!Defaults
qs: bar=xyzzy
url: "https://example.com/?foo=x"
---
!URLEncode
    url: !Var url
    query: !Var qs
""")
    assert template.enrich({}) == ['https://example.com/?foo=x&bar=xyzzy']
Example #25
0
def test_late_enrich():
    template = Template.parse('''
!Defaults
x:
  y: 5
z: !Var x
---
workie: !Lookup x.y
no_workie: !Lookup z.y
''',
                              format='yaml')
    assert template.enrich({}) == [{'workie': 5, 'no_workie': 5}]
Example #26
0
def test_no_index_start_with_dict():
    template = Template.parse('''
!Loop
  over:
    a: 5
  index_as: index
  index_start: 5
  template: 1
''')
    with pytest.raises(ValueError) as nope:
        template.render({})

    assert 'index_start with dict' in str(nope.value)
Example #27
0
def test_concat_var():
    """
    Concat must also support concatenating non-literal lists, ie. return values
    of list-valued tags.
    """
    assert Template.parse('''
!Defaults
a:
  - [1, 2, 3]
  - [4, 5, 6]
---
!Concat,Var a
''')
Example #28
0
def test_include_text_and_base64():
    filename = os.path.join(BASE_DIR, 'test_include_text_and_base64.in.yml')
    template = Template.parse('''
apiVersion: v1
kind: ConfigMap
metadata:
  name: config
data:
  image.png.b64: !IncludeBase64 includes/intense50.png
  config.toml: !IncludeText includes/data.toml
''', filename=filename)
    data = template.enrich({})[0]['data']
    assert data['image.png.b64'].startswith('iVBORw0KGgoAAAANSUhEUgA')
    assert data['config.toml'].startswith('[database]\nserver =')
Example #29
0
def test_filter_dict():
    template = Template.parse(
        '''
!Filter
  as: i
  test: !Not,Var i
  over:
    'yes': true
    no: 0
    nope: false
    oui: 1
''',
        'yaml',
    )
    assert template.enrich({})[0] == {False: 0, 'nope': False}
Example #30
0
def test_compose_context():
    """
    There was a bug in handling of Context in Compose that would cause Loop within Compose
    to not propagate `as`, `index_as` etc within `template`. Prior to fixing of that bug,
    this test would `KeyError: item`.
    """
    template = Template.parse('''
!Concat,Loop
  over:
    - [1, 2, 3]
    - [4, 5, 6]
  as: item
  template: !Var item
''')
    assert template.enrich({}) == [[1, 2, 3, 4, 5, 6]]