# test code for filters
# Copyright: (c) 2014, Michael DeHaan <michael.dehaan@gmail.com>
# Copyright: (c) 2019, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

- set_fact:
    output_dir: "{{ lookup('env', 'OUTPUT_DIR') }}"

- name: a dummy task to test the changed and success filters
  shell: echo hi
  register: some_registered_var

- debug:
    var: some_registered_var

- name: Verify that we workaround a py26 json bug
  template:
    src: py26json.j2
    dest: "{{ output_dir }}/py26json.templated"
    mode: 0644

- name: 9851 - Verify that we don't trigger https://github.com/ansible/ansible/issues/9851
  copy:
    content: " [{{ item | to_nice_json }}]"
    dest: "{{ output_dir }}/9851.out"
  with_items:
  - {"k": "Quotes \"'\n"}

- name: 9851 - copy known good output into place
  copy:
    src: 9851.txt
    dest: "{{ output_dir }}/9851.txt"

- name: 9851 - Compare generated json to known good
  shell: diff -w {{ output_dir }}/9851.out {{ output_dir }}/9851.txt
  register: diff_result_9851

- name: 9851 - verify generated file matches known good
  assert:
    that:
        - 'diff_result_9851.stdout == ""'

- name: fill in a basic template
  template:
    src: foo.j2
    dest: "{{ output_dir }}/foo.templated"
    mode: 0644
  register: template_result

- name: copy known good into place
  copy:
    src: foo.txt
    dest: "{{ output_dir }}/foo.txt"

- name: compare templated file to known good
  shell: diff -w {{ output_dir }}/foo.templated {{ output_dir }}/foo.txt
  register: diff_result

- name: verify templated file matches known good
  assert:
    that:
      - 'diff_result.stdout == ""'

- name: Verify human_readable
  tags: "human_readable"
  assert:
    that:
      - '"1.00 Bytes" == 1|human_readable'
      - '"1.00 bits" == 1|human_readable(isbits=True)'
      - '"10.00 KB" == 10240|human_readable'
      - '"97.66 MB" == 102400000|human_readable'
      - '"0.10 GB" == 102400000|human_readable(unit="G")'
      - '"0.10 Gb" == 102400000|human_readable(isbits=True, unit="G")'

- name: Verify human_to_bytes
  tags: "human_to_bytes"
  assert:
    that:
      - "{{'0'|human_to_bytes}}        == 0"
      - "{{'0.1'|human_to_bytes}}      == 0"
      - "{{'0.9'|human_to_bytes}}      == 1"
      - "{{'1'|human_to_bytes}}        == 1"
      - "{{'10.00 KB'|human_to_bytes}} == 10240"
      - "{{   '11 MB'|human_to_bytes}} == 11534336"
      - "{{  '1.1 GB'|human_to_bytes}} == 1181116006"
      - "{{'10.00 Kb'|human_to_bytes(isbits=True)}} == 10240"

- name: Verify human_to_bytes (bad string)
  set_fact:
    bad_string: "{{ '10.00 foo' | human_to_bytes }}"
  ignore_errors: yes
  tags: human_to_bytes
  register: _human_bytes_test

- name: Verify human_to_bytes (bad string)
  tags: human_to_bytes
  assert:
    that: "{{_human_bytes_test.failed}}"

- name: Test extract
  assert:
    that:
      - '"c" == 2 | extract(["a", "b", "c"])'
      - '"b" == 1 | extract(["a", "b", "c"])'
      - '"a" == 0 | extract(["a", "b", "c"])'

- name: Container lookups with extract
  assert:
    that:
      - "'x' == [0]|map('extract',['x','y'])|list|first"
      - "'y' == [1]|map('extract',['x','y'])|list|first"
      - "42 == ['x']|map('extract',{'x':42,'y':31})|list|first"
      - "31 == ['x','y']|map('extract',{'x':42,'y':31})|list|last"
      - "'local' == ['localhost']|map('extract',hostvars,'ansible_connection')|list|first"
      - "'local' == ['localhost']|map('extract',hostvars,['ansible_connection'])|list|first"
  # map was added to jinja2 in version 2.7
  when: "{{ ( lookup('pipe', '{{ ansible_python[\"executable\"] }} -c \"import jinja2; print(jinja2.__version__)\"')  is version('2.7', '>=') ) }}"

- name: Test json_query filter
  assert:
    that:
      - "users | json_query('[*].hosts[].host') == ['host_a', 'host_b', 'host_c', 'host_d']"

- name: Test hash filter
  assert:
    that:
      - '"{{ "hash" | hash("sha1") }}" == "2346ad27d7568ba9896f1b7da6b5991251debdf2"'
      - '"{{ "café" | hash("sha1") }}" == "f424452a9673918c6f09b0cdd35b20be8e6ae7d7"'

- debug:
    var: "'http://mary:MySecret@www.acme.com:9000/dir/index.html?query=term#fragment' | urlsplit"
    verbosity: 1
  tags: debug

- name: Test urlsplit filter
  assert:
    that:
      - "'http://mary:MySecret@www.acme.com:9000/dir/index.html?query=term#fragment' | urlsplit('fragment') == 'fragment'"
      - "'http://mary:MySecret@www.acme.com:9000/dir/index.html?query=term#fragment' | urlsplit('hostname') == 'www.acme.com'"
      - "'http://mary:MySecret@www.acme.com:9000/dir/index.html?query=term#fragment' | urlsplit('netloc') == 'mary:MySecret@www.acme.com:9000'"
      - "'http://mary:MySecret@www.acme.com:9000/dir/index.html?query=term#fragment' | urlsplit('path') == '/dir/index.html'"
      - "'http://mary:MySecret@www.acme.com:9000/dir/index.html?query=term#fragment' | urlsplit('port') == 9000"
      - "'http://mary:MySecret@www.acme.com:9000/dir/index.html?query=term#fragment' | urlsplit('query') == 'query=term'"
      - "'http://mary:MySecret@www.acme.com:9000/dir/index.html?query=term#fragment' | urlsplit('scheme') == 'http'"
      - "'http://mary:MySecret@www.acme.com:9000/dir/index.html?query=term#fragment' | urlsplit('username') == 'mary'"
      - "'http://mary:MySecret@www.acme.com:9000/dir/index.html?query=term#fragment' | urlsplit('password') == 'MySecret'"
      - "'http://mary:MySecret@www.acme.com:9000/dir/index.html?query=term#fragment' | urlsplit == { 'fragment': 'fragment', 'hostname': 'www.acme.com', 'netloc': 'mary:MySecret@www.acme.com:9000', 'password': 'MySecret', 'path': '/dir/index.html', 'port': 9000, 'query': 'query=term', 'scheme': 'http', 'username': 'mary' }"


- name: Test urlsplit filter bad argument
  debug:
    var: "'http://www.acme.com:9000/dir/index.html' | urlsplit('bad_filter')"
  register: _bad_urlsplit_filter
  ignore_errors: yes

- name: Verify urlsplit filter showed an error message
  assert:
    that:
      - _bad_urlsplit_filter is failed
      - "'unknown URL component' in _bad_urlsplit_filter.msg"

- name: Test urldecode filter
  set_fact:
    urldecoded_string: key="@{}é&%£ foo bar '(;\<>""°)

- name: Test urlencode filter
  set_fact:
    urlencoded_string: '{{ urldecoded_string|urlencode }}'

- name: Verify urlencode en urldecode
  assert:
    that:
    - urldecoded_string == urlencoded_string|urldecode

- name: Flatten tests
  block:
    - name: use flatten
      set_fact:
        flat_full: '{{orig_list|flatten}}'
        flat_one: '{{orig_list|flatten(levels=1)}}'
        flat_two: '{{orig_list|flatten(levels=2)}}'
        flat_tuples: '{{ [1,3] | zip([2,4]) | list | flatten }}'

    - name: Verify flatten filter works as expected
      assert:
        that:
          - flat_full == [1, 2, 3, 4, 5, 6, 7]
          - flat_one == [1, 2, 3, [4, [5]], 6, 7]
          - flat_two == [1, 2, 3, 4, [5], 6, 7]
          - flat_tuples == [1, 2, 3, 4]
  vars:
    orig_list: [1, 2, [3, [4, [5]], 6], 7]

- name: Test base64 filter
  assert:
    that:
    - "'Ansible - くらとみ\n' | b64encode == 'QW5zaWJsZSAtIOOBj+OCieOBqOOBvwo='"
    - "'QW5zaWJsZSAtIOOBj+OCieOBqOOBvwo=' | b64decode == 'Ansible - くらとみ\n'"
    - "'Ansible - くらとみ\n' | b64encode(encoding='utf-16-le') == 'QQBuAHMAaQBiAGwAZQAgAC0AIABPMIkwaDB/MAoA'"
    - "'QQBuAHMAaQBiAGwAZQAgAC0AIABPMIkwaDB/MAoA' | b64decode(encoding='utf-16-le') == 'Ansible - くらとみ\n'"

- name: Test random_mac filter bad argument type
  debug:
    var: "0 | random_mac"
  register: _bad_random_mac_filter
  ignore_errors: yes

- name: Verify random_mac filter showed a bad argument type error message
  assert:
    that:
      - _bad_random_mac_filter is failed
      - "_bad_random_mac_filter.msg is match('Invalid value type (.*int.*) for random_mac .*')"

- name: Test random_mac filter bad argument value
  debug:
    var: "'dummy' | random_mac"
  register: _bad_random_mac_filter
  ignore_errors: yes

- name: Verify random_mac filter showed a bad argument value error message
  assert:
    that:
      - _bad_random_mac_filter is failed
      - "_bad_random_mac_filter.msg is match('Invalid value (.*) for random_mac: .* not hexa byte')"

- name: Test random_mac filter prefix too big
  debug:
    var: "'00:00:00:00:00:00' | random_mac"
  register: _bad_random_mac_filter
  ignore_errors: yes

- name: Verify random_mac filter showed a prefix too big error message
  assert:
    that:
      - _bad_random_mac_filter is failed
      - "_bad_random_mac_filter.msg is match('Invalid value (.*) for random_mac: 5 colon.* separated items max')"

- name:  Verify random_mac filter
  assert:
    that:
            - "'00' | random_mac is match('^00:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]$')"
            - "'00:00' | random_mac is match('^00:00:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]$')"  
            - "'00:00:00' | random_mac is match('^00:00:00:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]$')"
            - "'00:00:00:00' | random_mac is match('^00:00:00:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]:[a-f0-9][a-f0-9]$')"
            - "'00:00:00:00:00' | random_mac is match('^00:00:00:00:00:[a-f0-9][a-f0-9]$')"  
            - "'00:00:00' | random_mac != '00:00:00' | random_mac"

- name: Verify random_mac filter with seed
  assert:
    that:
      - "'00:00:00' | random_mac(seed='test') == '00:00:00' | random_mac(seed='test')"
      - "'00:00:00' | random_mac(seed='test') != '00:00:00' | random_mac(seed='another_test')"

- name: Verify that union can be chained
  vars:
    unions: '{{ [1,2,3]|union([4,5])|union([6,7]) }}'
  assert:
    that:
      - "unions|type_debug == 'list'"
      - "unions|length == 7"

- name: Test union with unhashable item
  vars:
    unions: '{{ [1,2,3]|union([{}]) }}'
  assert:
    that:
      - "unions|type_debug == 'list'"
      - "unions|length == 4"

- name: Test ipaddr filter
  assert:
    that:
      - "'192.168.0.1/32' | ipaddr('netmask') == '255.255.255.255'"
      - "'192.168.0.1/24' | ipaddr('netmask') == '255.255.255.0'"
      - "not '192.168.0.1/31' | ipaddr('broadcast')"
      - "'192.168.0.1/24' | ipaddr('broadcast') == '192.168.0.255'"
      - "'192.168.0.1/24' | ipaddr('prefix') == 24"
      - "'192.168.0.1/24' | ipaddr('address') == '192.168.0.1'"
      - "'192.168.0.1/24' | ipaddr('network') == '192.168.0.0'"
      - "'fe80::dead:beef/64' | ipaddr('broadcast') == 'fe80::ffff:ffff:ffff:ffff'"
      - "'::1/120' | ipaddr('netmask') == 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff00'"
      - "{{ subnets | ipaddr(1) }} == ['10.1.1.1/24', '10.1.2.1/24']"
      - "{{ subnets | ipaddr('1') }}  == ['10.1.1.1/24', '10.1.2.1/24']"
      - "{{ subnets | ipaddr(-1) }} == ['10.1.1.255/24', '10.1.2.255/24']"
      - "{{ subnets | ipaddr('-1') }} == ['10.1.1.255/24', '10.1.2.255/24']"
      - "'{{ prefix | ipaddr(1) }}'  == '10.1.1.1/24'"
      - "'{{ prefix | ipaddr('1') }}' == '10.1.1.1/24'"
      - "'{{ prefix | ipaddr('network') }}' == '10.1.1.0'"
      - "'{{ prefix | ipaddr('-1') }}' == '10.1.1.255/24'"
  vars:
    subnets: ['10.1.1.0/24', '10.1.2.0/24']
    prefix: '10.1.1.0/24'

- name: Ensure dict2items works with hostvars
  debug:
    msg: "{{ item.key }}"
  loop: "{{ hostvars|dict2items }}"
  loop_control:
    label: "{{ item.key }}"

- name: Ensure combining two dictionaries containing undefined variables provides a helpful error
  block:
    - set_fact:
        foo:
          key1: value1

    - set_fact:
        combined: "{{ foo | combine({'key2': undef_variable}) }}"
      ignore_errors: yes
      register: result

    - assert:
        that:
          - "result.msg.startswith('The task includes an option with an undefined variable')"

    - set_fact:
        combined: "{{ foo | combine({'key2': {'nested': [undef_variable]}})}}"
      ignore_errors: yes
      register: result

    - assert:
        that:
          - "result.msg.startswith('The task includes an option with an undefined variable')"

    - set_fact:
        key2: is_defined

    - set_fact:
        combined: "{{ foo | combine({'key2': key2}) }}"

    - assert:
        that:
          - "combined.key2 == 'is_defined'"
