Exemplo n.º 1
0
def test_sub_table():
    sub_menu_1_items = [
        TableItem("sub menu 1: Choice 1", 1, TABLE_ITEM_DEFAULT),
        TableItem("sub menu 1: Choice 2", 2, TABLE_ITEM_DEFAULT),
    ]
    use_style = TableStyle(show_cols=False,
                           show_border=False,
                           hrules=RULE_NONE,
                           vrules=RULE_NONE)
    sub_menu_1 = Table(sub_menu_1_items,
                       title="Sub-Menu 2",
                       add_exit=TABLE_ADD_RETURN,
                       style=use_style)

    # call submenus two different ways. First by using it as a callable, which calls run on the sub_menu, and second
    # with an explicit action handler
    menu_choices = [
        TableItem("Choice 1", None, TABLE_ITEM_DEFAULT),
        TableItem("sub_menu 1", None, sub_menu_1),
        TableItem("sub_menu 2", None, sub_menu_action),
    ]

    print('\nmenu.run - with sub-menu\n')
    use_style = TableStyle(show_cols=False,
                           show_border=False,
                           hrules=RULE_NONE,
                           vrules=RULE_NONE)
    menu = Table(menu_choices, add_exit=True, style=use_style)
    menu.run()
    print('done')
Exemplo n.º 2
0
    def test_table_of_tablestyles(self):
        input_str = '3'

        print('\nTest list of class instances (autogen tags)\n')

        items = [
            TableStyle(True, True, RULE_FRAME, RULE_FRAME),
            TableStyle(True, False, RULE_FRAME, RULE_FRAME),
            TableStyle(False, True, RULE_ALL, RULE_FRAME),
            TableStyle(False, False, RULE_FRAME, RULE_ALL),
        ]
        fields = 'show_cols hrules vrules'.split()  # no show_border on purpose
        field_names = 'Show_Cols H-Rules V-Rules'.split()
        table_style = TableStyle(show_cols=True,
                                 show_border=True,
                                 hrules=RULE_FRAME,
                                 vrules=RULE_ALL)
        gen_tags = True
        tag_str = "Table Style"
        with redirect_stdin(StringIO(input_str)):
            result = use_create_table(items,
                                      fields,
                                      field_names,
                                      gen_tags,
                                      tag_str,
                                      style=table_style)
        assert (result == [3, False, 1, 0])
Exemplo n.º 3
0
    def test_dict_of_lists(self):
        input_str = '3'

        print('\nTest list of dictionary of lists (autogen tags)\n')

        items = {
            1: ["Beast", "IO-PROD", "Model One G2"],
            2: ["Ford2", "Dearborn", "Model One G2.1"],
            3: ["Seth", "IO-PROD", "Cell"]
        }
        fields = 'name location model'.split()
        field_names = 'Name Location IO_Model'.split()
        table_style = TableStyle(show_cols=True,
                                 show_border=True,
                                 hrules=RULE_FRAME,
                                 vrules=RULE_ALL)
        gen_tags = True
        tag_str = "Printer"
        with redirect_stdin(StringIO(input_str)):
            result = use_create_table(items,
                                      fields,
                                      field_names,
                                      gen_tags,
                                      tag_str,
                                      style=table_style)
        assert (result == [3, "Seth", "IO-PROD", "Cell"])
Exemplo n.º 4
0
    def test_multi_item_list(self):
        input_str = 'Ford2'

        print('\nTest list of multiple items (no autogen tags)\n')
        items = [["Beast", "IO-PROD", "Model One G2"],
                 ["Ford2", "Dearborn", "Model One G2.1"],
                 ["Seth", "IO-PROD", "Cell"]]
        fields = 'name location model'.split()
        field_names = 'Name Location IO_Model'.split()
        table_style = TableStyle(show_cols=True,
                                 show_border=True,
                                 hrules=RULE_FRAME,
                                 vrules=RULE_ALL)
        gen_tags = False
        tag_str = None
        with redirect_stdin(StringIO(input_str)):
            result = use_create_table(items,
                                      fields,
                                      field_names,
                                      gen_tags,
                                      tag_str,
                                      style=table_style)
        print('result is...' + str(result))
        # assert (result[0] == 'Ford2' )
        assert (result == ["Ford2", "Dearborn", "Model One G2.1"])
Exemplo n.º 5
0
    def test_single_item_table(self):
        input_str = 'Beast'

        print('\nTest list of single items (no autogen tags)\n')
        prompt = None
        items = [["Beast"], ["Deuce"], ["Seth"]]  # single item list
        fields = 'name'.split()
        field_names = 'Name'.split()
        table_style = TableStyle(show_cols=True,
                                 show_border=True,
                                 hrules=RULE_FRAME,
                                 vrules=RULE_ALL)
        gen_tags = False
        tag_str = 'Printer'
        add_exit = True
        with redirect_stdin(StringIO(input_str)):
            result = use_create_table(items,
                                      fields,
                                      field_names,
                                      gen_tags,
                                      tag_str,
                                      add_exit=add_exit,
                                      prompt=prompt,
                                      style=table_style)

        print('result is...' + str(result))
        assert (result == ['Beast'])
Exemplo n.º 6
0
    def test_get_table_single_autogen(self):
        # single item list, generate tags
        input_str = '2'

        print('\nTest list of single items - autogen tags\n')
        table_style = TableStyle(show_cols=True,
                                 show_border=True,
                                 hrules=RULE_FRAME,
                                 vrules=RULE_ALL)
        items = [["Beast"], ["Deuce"], ["Seth"]]  # single item list
        fields = 'name'.split()
        field_names = 'Name'.split()
        gen_tags = True
        tag_str = ''
        prompt = 'Choose a printer'

        with redirect_stdin(StringIO(input_str)):
            result = use_create_table(items,
                                      fields,
                                      field_names,
                                      gen_tags,
                                      tag_str,
                                      prompt=prompt,
                                      style=table_style)
        assert (result == [2, 'Deuce'])
Exemplo n.º 7
0
def test_refresh_table():
    print('test refresh option in a menu:\n')
    my_profile = {'first': 'Len', 'last': 'Wanger'}

    menu_choices = [
        TableItem("Change first name from: {first}", None, change_first_name),
        TableItem("Change last name from: {last}", None, change_last_name),
        TableItem(
            "Change kwargs to Dick Ellis with lambda", None,
            lambda tag, ad: ad.update({
                'first': 'Dick',
                'last': 'Ellis'
            })),
        TableItem("call default action (print args and kwargs)", None,
                  TABLE_ITEM_DEFAULT),
        TableItem("call action_1 (print args and kwargs)", None, action_1),
    ]

    print('\nmenu.run - dynamic labels - now w/ refresh\n')
    use_style = TableStyle(show_cols=False,
                           show_border=False,
                           hrules=RULE_NONE,
                           vrules=RULE_NONE)
    menu = Table(menu_choices,
                 add_exit=True,
                 style=use_style,
                 default_action=default_action,
                 action_dict=my_profile,
                 refresh=True)
    menu.run()

    print('done')
Exemplo n.º 8
0
def test_args_table():
    print('test sending args and kwargs to menus:\n')

    menu_choices = [
        TableItem("Change kwargs to Ron McGee", None, change_kwargs),
        TableItem("Change kwargs to Len Wanger", None, change_kwargs),
        TableItem(
            "Change kwargs to Dick Ellis with lambda", None,
            lambda tag, ad: ad.update({
                'first': 'Dick',
                'last': 'Ellis'
            })),
        TableItem("call default action (print args and kwargs)", None,
                  TABLE_ITEM_DEFAULT),
        TableItem("call action_1 (print args and kwargs)", None, action_1),
    ]

    my_profile = {'first': 'Len', 'last': 'Wanger'}

    print('\nmenu.run - with sub-menu\n')
    use_style = TableStyle(show_cols=False,
                           show_border=False,
                           hrules=RULE_NONE,
                           vrules=RULE_NONE)
    menu = Table(menu_choices,
                 add_exit=True,
                 style=use_style,
                 default_action=default_action,
                 action_dict=my_profile)
    menu.run()
    print('done')
Exemplo n.º 9
0
def test_dynamic_menu_from_list(filter_items=False):
    users = [{
        'name': 'ed',
        'fullname': 'Ed Jones',
        'password': '******'
    }, {
        'name': 'wendy',
        'fullname': 'Wendy Williams',
        'password': '******'
    }, {
        'name': 'mary',
        'fullname': 'Mary Contrary',
        'password': '******'
    }, {
        'name': 'leonard',
        'fullname': 'Leonard Nemoy',
        'password': '******'
    }, {
        'name': 'fred',
        'fullname': 'Fred Flintstone',
        'password': '******'
    }]

    action_dict = {'min_len': 4}
    tis = [menu_item_factory2(user, 4) for user in users]
    tis.append(
        TableItem('Set minimum length ({min_len})',
                  'filter',
                  set_filter_len_action,
                  hidden=True,
                  item_data={
                      'no_filter': True
                  }))  # no_filter tells item_filter not to filter the item

    header = 'Showing users with user length > {min_len}\n'
    footer = 'type "filter" to change minimum length'
    use_style = TableStyle(show_cols=False,
                           show_border=False,
                           hrules=RULE_NONE,
                           vrules=RULE_NONE)
    menu = Table(rows=tis,
                 add_exit=True,
                 style=use_style,
                 action_dict=action_dict,
                 header=header,
                 footer=footer,
                 item_filter=user_filter2)
    menu()
Exemplo n.º 10
0
def sub_menu_action(row, action_dict):
    print('sub_menu2: row={}, action_dict={}'.format(row, action_dict))

    sub_menu_choices = [
        TableItem("sub menu 2: Choice 1", 1, TABLE_ITEM_DEFAULT),
        TableItem("sub menu 2: Choice 2", 2, TABLE_ITEM_DEFAULT),
    ]
    use_style = TableStyle(show_cols=False,
                           show_border=False,
                           hrules=RULE_NONE,
                           vrules=RULE_NONE)
    sub_menu = Table(sub_menu_choices,
                     title="Sub-Menu 2",
                     add_exit=TABLE_ADD_RETURN,
                     style=use_style)
    sub_menu.run()
Exemplo n.º 11
0
def test_dynamic_menu_from_db(filter_items=False):
    engine = create_engine('sqlite:///:memory:', echo=True)
    Base.metadata.create_all(engine)

    session_maker = sessionmaker(bind=engine)
    session = session_maker()

    session.add_all([
        User(name='ed', fullname='Ed Jones', password='******'),
        User(name='wendy', fullname='Wendy Williams', password='******'),
        User(name='mary', fullname='Mary Contrary', password='******'),
        User(name='fred', fullname='Fred Flinstone', password='******')
    ])

    session.commit()

    qry = session.query(User.name, User.fullname).order_by(User.fullname)
    tis = [menu_item_factory(row, item_data={'min_len': 3}) for row in qry]
    for row in tis:
        print(row)

    print('adding foo'
          )  # show that the stored query will update with data changes
    session.add(User(name='foo', fullname='Foo Winn', password='******'))
    session.commit()
    use_style = TableStyle(show_cols=False,
                           show_border=False,
                           hrules=RULE_NONE,
                           vrules=RULE_NONE)

    if filter_items:
        menu = Table(rows=tis,
                     add_exit=True,
                     style=use_style,
                     item_filter=user_filter)
    else:
        menu = Table(rows=tis, add_exit=True, style=use_style)

    menu()
Exemplo n.º 12
0
    def test_named_tuple(self):
        input_str = '3'
        print('\nTest list of named tuples (autogen tags)\n')

        MyTuple = namedtuple("MyTuple", "name location model other")
        items = [
            MyTuple("Beast", "IO-PROD", "Model One G2", "Other stuff"),
            MyTuple("Ford2", "Dearborn", "Model One G2.1", "Other stuff"),
            MyTuple("Seth", "IO-PROD", "Cell", "Seth Other stuff"),
        ]
        fields = 'name location model'.split()
        field_names = 'Name Location IO_Model'.split()
        table_style = TableStyle(show_cols=True,
                                 show_border=True,
                                 hrules=RULE_FRAME,
                                 vrules=RULE_ALL)
        gen_tags = True
        tag_str = None
        aitid = True
        default_action = TABLE_RETURN_TABLE_ITEM
        with redirect_stdin(StringIO(input_str)):
            ti = use_create_table(items,
                                  fields,
                                  field_names,
                                  gen_tags,
                                  tag_str,
                                  item_data=None,
                                  add_item_to_item_data=aitid,
                                  style=table_style,
                                  default_action=default_action)

        print(
            f'name={ti.item_data["item"].name},  other={ti.item_data["item"].other}'
        )
        assert (ti.item_data['item'].name == 'Seth')
        assert (ti.tag == 3)
Exemplo n.º 13
0
def test_item_filter():
    all_roles = {'roles': {'admin', 'user'}}
    admin_only = {'roles': {'admin'}}

    menu_choices = [
        TableItem("Change roles from: {roles}",
                  None,
                  change_roles,
                  item_data=all_roles),
        TableItem("Change roles to: 'admin'",
                  None,
                  lambda tag, ad: ad.update({'roles': {'admin'}}),
                  item_data=all_roles),
        TableItem("call default action (print args and kwargs) - admin only!",
                  None,
                  lambda tag, ad: print('roles={}'.format(ad['roles'])),
                  item_data=admin_only),
        TableItem("call show_roles", None, show_roles),
    ]

    print('\nmenu.run\n')
    my_profile = {'first': 'Len', 'last': 'Wanger', 'roles': ['user']}
    use_style = TableStyle(show_cols=False,
                           show_border=False,
                           hrules=RULE_NONE,
                           vrules=RULE_NONE)
    menu = Table(menu_choices,
                 add_exit=True,
                 style=use_style,
                 default_action=default_action,
                 action_dict=my_profile,
                 refresh=True,
                 item_filter=role_item_filter)
    menu.run()

    print('done')
Exemplo n.º 14
0
        return 'Better dead than red!'


def return_rgb_action(row, action_dict):
    return row.values[2]


if __name__ == '__main__':
    table_items = [
        TableItem('red'),
        TableItem('blue'),
        TableItem('green'),
    ]

    style_1 = TableStyle(show_cols=False,
                         show_border=False,
                         hrules=RULE_NONE,
                         vrules=RULE_NONE)

    # simplest way
    table = Table(table_items, col_names=['Color'])
    tag = get_table_input(table)
    print('\ntag={}\n'.format(tag))

    # simplest way (style -- no borders)
    table = Table(table_items, col_names=['Color'], style=style_1)
    tag = get_table_input(table)
    print('\ntag={}\n'.format(tag))

    # get value from table with specified default action (get values[0] - color name)
    table = Table(table_items,
                  col_names=['Color'],
Exemplo n.º 15
0
def test_action_table():
    menu_choices = [
        TableItem("Choice 1 - no specified tag, no specified action", None,
                  None),
        TableItem("Choice 2 - default action", 2, TABLE_ITEM_DEFAULT),
        TableItem(
            "Choice 3 - text tag, lambda action", 'foo', lambda row, kwargs:
            print('lambda action: row={}, kwargs={}'.format(row, kwargs))),
        TableItem("Choice 4 - text tag, action handler function specified",
                  'bar', action_1),
        TableItem("STOP the menu!", 'stop', TABLE_ITEM_EXIT),
    ]

    print('\nget_table_choice - add_exit=True\n')
    use_style = TableStyle(show_cols=False,
                           show_border=False,
                           vrules=RULE_NONE)
    menu = Table(menu_choices[:-1], add_exit=True, tag_str="", style=use_style)
    choice = menu.get_table_choice()
    show_choice(menu, choice)

    print(
        '\nget_table_choice - add_exit=False (no exit!), case_sensitive=True, with title, no columns\n'
    )
    use_style = TableStyle(show_cols=False, show_border=True, vrules=RULE_NONE)
    menu = Table(menu_choices[:-1],
                 title='My Menu:',
                 add_exit=False,
                 case_sensitive=True,
                 style=use_style)
    choice = menu.get_table_choice()
    show_choice(menu, choice)

    print(
        '\nget_table_choice - add_exit=False, w/ prompt, default="stop", hrule=ALL, vrule=NONE\n'
    )
    use_style = TableStyle(show_cols=False, hrules=RULE_ALL, vrules=RULE_NONE)
    menu = Table(menu_choices,
                 prompt='Choose or die!',
                 default_choice='stop',
                 default_action=default_action,
                 add_exit=False,
                 style=use_style)
    choice = menu.get_table_choice()
    show_choice(menu, choice)

    print(
        '\nget_table_choice - add_exit=False, w/ prompt, default="stop", no columns, no border\n'
    )
    use_style = TableStyle(show_cols=False,
                           show_border=False,
                           hrules=RULE_NONE,
                           vrules=RULE_NONE)
    menu = Table(menu_choices,
                 prompt='Choose or die!',
                 default_choice='stop',
                 default_action=default_action,
                 add_exit=False,
                 show_border=False,
                 show_cols=False)
    choice = menu.get_table_choice()
    show_choice(menu, choice)

    print('\nmenu.run - add_exit=True\n')
    menu.add_exit = True
    menu.run()
    print('done')