File: test_bind_namedtuple.py

package info (click to toggle)
python-cyclopts 3.12.0-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,288 kB
  • sloc: python: 11,445; makefile: 24
file content (76 lines) | stat: -rw-r--r-- 1,921 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import sys
from collections import namedtuple
from typing import NamedTuple

import pytest


def test_bind_typing_named_tuple(app, assert_parse_args):
    class Employee(NamedTuple):
        name: str
        id: int = 3

    @app.command
    def foo(user: Employee):
        pass

    assert_parse_args(
        foo,
        'foo --user.name="John Smith" --user.id=100',
        Employee(name="John Smith", id=100),
    )

    assert_parse_args(
        foo,
        'foo "John Smith" 100',
        Employee(name="John Smith", id=100),
    )


def test_bind_typing_named_tuple_var_positional(app, assert_parse_args):
    class Employee(NamedTuple):
        name: str
        id: int

    @app.command
    def foo(*users: Employee):
        pass

    assert_parse_args(
        foo,
        'foo "John Smith" 100 "Mary Jones" 200',
        Employee(name="John Smith", id=100),
        Employee(name="Mary Jones", id=200),
    )


@pytest.mark.skipif(sys.version_info < (3, 10), reason="<3.10 does not have __annotations__ field.")
def test_bind_collections_named_tuple(app, assert_parse_args):
    # All fields will be strings since cyclopts doesn't know the types.
    Employee = namedtuple("Employee", ["name", "id"])

    @app.command
    def foo(user: Employee):
        pass

    assert_parse_args(
        foo,
        'foo --user.name="John Smith" --user.id=100',
        Employee(name="John Smith", id="100"),
    )


@pytest.mark.skipif(sys.version_info > (3, 9), reason="namedtuple fully supported.")
def test_bind_collections_named_tuple_unsupported(app, assert_parse_args):
    # All fields will be strings since cyclopts doesn't know the types.
    Employee = namedtuple("Employee", ["name", "id"])

    @app.command
    def foo(user: Employee):
        pass

    with pytest.raises(ValueError):
        assert_parse_args(
            foo,
            'foo --user.name="John Smith" --user.id=100',
        )