Esempio n. 1
0
def test_pandas_groupby_apply():
    """Test pandas.DataFrame.groupby(...).progress_apply"""
    try:
        from numpy.random import randint
        import pandas as pd
    except ImportError:
        raise SkipTest

    with closing(StringIO()) as our_file:
        tqdm.pandas(file=our_file, leave=False, ascii=True)

        df = pd.DataFrame(randint(0, 50, (500, 3)))
        df.groupby(0).progress_apply(lambda x: None)

        dfs = pd.DataFrame(randint(0, 50, (500, 3)), columns=list('abc'))
        dfs.groupby(['a']).progress_apply(lambda x: None)

        our_file.seek(0)

        # don't expect final output since no `leave` and
        # high dynamic `miniters`
        nexres = '100%|##########|'
        if nexres in our_file.read():
            our_file.seek(0)
            raise AssertionError("\nDid not expect:\n{0}\nIn:{1}\n".format(
                nexres, our_file.read()))

    with closing(StringIO()) as our_file:
        tqdm.pandas(file=our_file, leave=True, ascii=True)

        dfs = pd.DataFrame(randint(0, 50, (500, 3)), columns=list('abc'))
        dfs.loc[0] = [2, 1, 1]
        dfs['d'] = 100

        expects = ['500/500', '1/1', '4/4', '2/2']
        dfs.groupby(dfs.index).progress_apply(lambda x: None)
        dfs.groupby('d').progress_apply(lambda x: None)
        dfs.groupby(dfs.columns, axis=1).progress_apply(lambda x: None)
        dfs.groupby([2, 2, 1, 1], axis=1).progress_apply(lambda x: None)

        our_file.seek(0)
        if our_file.read().count('100%') < 4:
            our_file.seek(0)
            raise AssertionError("\nExpected:\n{0}\nIn:\n{1}\n".format(
                '100% at least four times', our_file.read()))

        for exres in expects:
            our_file.seek(0)
            if our_file.getvalue().count(exres) < 1:
                our_file.seek(0)
                raise AssertionError(
                    "\nExpected:\n{0}\nIn:\n {1}\n".format(
                        exres + " at least once.", our_file.read()))
Esempio n. 2
0
def test_main():
    """Test command line pipes"""
    ls_out = _sh('ls').replace('\r\n', '\n')
    ls = subprocess.Popen('ls', stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT)
    res = _sh(sys.executable, '-c', 'from tqdm import main; main()',
              stdin=ls.stdout, stderr=subprocess.STDOUT)
    ls.wait()

    # actual test:

    assert ls_out in res.replace('\r\n', '\n')

    # semi-fake test which gets coverage:
    _SYS = sys.stdin, sys.argv

    with closing(StringIO()) as sys.stdin:
        sys.argv = ['', '--desc', 'Test CLI --delim',
                    '--ascii', 'True', '--delim', r'\0', '--buf_size', '64']
        sys.stdin.write('\0'.join(map(str, _range(int(123)))))
        #sys.stdin.write(b'\xff')  # TODO
        sys.stdin.seek(0)
        main()
    sys.stdin = IN_DATA_LIST

    sys.argv = ['', '--desc', 'Test CLI pipes',
                '--ascii', 'True', '--unit_scale', 'True']
    import tqdm.__main__  # NOQA

    with closing(StringIO()) as sys.stdin:
        IN_DATA = '\0'.join(IN_DATA_LIST)
        sys.stdin.write(IN_DATA)
        sys.stdin.seek(0)
        sys.argv = ['', '--ascii', '--bytes', '--unit_scale', 'False']
        with closing(UnicodeIO()) as fp:
            main(fp=fp)
            assert str(len(IN_DATA)) in fp.getvalue()
    sys.stdin = IN_DATA_LIST

    # test --log
    with closing(StringIO()) as sys.stdin:
        sys.stdin.write('\0'.join(map(str, _range(int(123)))))
        sys.stdin.seek(0)
        # with closing(UnicodeIO()) as fp:
        main(argv=['--log', 'DEBUG'], fp=NULL)
        # assert "DEBUG:" in sys.stdout.getvalue()
    sys.stdin = IN_DATA_LIST

    # clean up
    sys.stdin, sys.argv = _SYS
Esempio n. 3
0
def test_pandas_groupby_apply():
    """ Test pandas.DataFrame.groupby(...).progress_apply """
    try:
        from numpy.random import randint
        from tqdm import tqdm_pandas
        import pandas as pd
    except:
        raise SkipTest

    with closing(StringIO()) as our_file:
        df = pd.DataFrame(randint(0, 50, (500, 3)))
        dfs = pd.DataFrame(randint(0, 50, (500, 3)),
                           columns=list('abc'))
        tqdm_pandas(tqdm(file=our_file, leave=False, ascii=True))
        df.groupby(0).progress_apply(lambda x: None)
        tqdm_pandas(tqdm(file=our_file, leave=False, ascii=True))
        dfs.groupby(['a']).progress_apply(lambda x: None)

        our_file.seek(0)

        # don't expect final output since no `leave` and
        # high dynamic `miniters`
        nexres = '100%|##########|'
        if nexres in our_file.read():
            our_file.seek(0)
            raise AssertionError("\nDid not expect:\n{0}\nIn:{1}\n".format(
                nexres, our_file.read()))
Esempio n. 4
0
def test_pandas_series():
    """Test pandas.Series.progress_apply and .progress_map"""
    try:
        from numpy.random import randint
        import pandas as pd
    except ImportError:
        raise SkipTest

    with closing(StringIO()) as our_file:
        tqdm.pandas(file=our_file, leave=True, ascii=True)

        series = pd.Series(randint(0, 50, (123,)))
        res1 = series.progress_apply(lambda x: x + 10)
        res2 = series.apply(lambda x: x + 10)
        assert res1.equals(res2)

        res3 = series.progress_map(lambda x: x + 10)
        res4 = series.map(lambda x: x + 10)
        assert res3.equals(res4)

        expects = ['100%', '123/123']
        for exres in expects:
            our_file.seek(0)
            if our_file.getvalue().count(exres) < 2:
                our_file.seek(0)
                raise AssertionError(
                    "\nExpected:\n{0}\nIn:\n{1}\n".format(
                        exres + " at least twice.", our_file.read()))
Esempio n. 5
0
def test_iter_overhead():
    """ Test overhead of iteration based tqdm """
    try:
        assert checkCpuTime()
    except:
        raise SkipTest

    total = int(1e6)

    with closing(MockIO()) as our_file:
        a = 0
        with relative_timer() as time_tqdm:
            for i in trange(total, file=our_file):
                a += i
        assert(a == (total * total - total) / 2.0)

        a = 0
        with relative_timer() as time_bench:
            for i in _range(total):
                a += i
                our_file.write(a)

    # Compute relative overhead of tqdm against native range()
    if time_tqdm() > 9 * time_bench():
        raise AssertionError('trange(%g): %f, range(%g): %f' %
                             (total, time_tqdm(), total, time_bench()))
Esempio n. 6
0
def test_pandas_rolling_expanding():
    """Test pandas.(Series|DataFrame).(rolling|expanding)"""
    try:
        from numpy.random import randint
        import pandas as pd
    except ImportError:
        raise SkipTest

    with closing(StringIO()) as our_file:
        tqdm.pandas(file=our_file, leave=True, ascii=True)

        series = pd.Series(randint(0, 50, (123,)))
        res1 = series.rolling(10).progress_apply(lambda x: 1, raw=True)
        res2 = series.rolling(10).apply(lambda x: 1, raw=True)
        assert res1.equals(res2)

        res3 = series.expanding(10).progress_apply(lambda x: 2, raw=True)
        res4 = series.expanding(10).apply(lambda x: 2, raw=True)
        assert res3.equals(res4)

        expects = ['114it']  # 123-10+1
        for exres in expects:
            our_file.seek(0)
            if our_file.getvalue().count(exres) < 2:
                our_file.seek(0)
                raise AssertionError(
                    "\nExpected:\n{0}\nIn:\n{1}\n".format(
                        exres + " at least twice.", our_file.read()))
Esempio n. 7
0
def test_manual_overhead():
    """ Test overhead of manual tqdm """
    try:
        assert checkCpuTime()
    except:
        raise SkipTest

    total = int(1e6)

    with closing(MockIO()) as our_file:
        with tqdm(total=total * 10, file=our_file, leave=True) as t:
            a = 0
            with relative_timer() as time_tqdm:
                for i in _range(total):
                    a += i
                    t.update(10)

        a = 0
        with relative_timer() as time_bench:
            for i in _range(total):
                a += i
                our_file.write(a)

    # Compute relative overhead of tqdm against native range()
    if time_tqdm() > 10 * time_bench():
        raise AssertionError('tqdm(%g): %f, range(%g): %f' %
                             (total, time_tqdm(), total, time_bench()))
Esempio n. 8
0
def test_iter_overhead_hard():
    """Test overhead of iteration based tqdm (hard)"""

    total = int(1e5)

    with closing(MockIO()) as our_file:
        a = 0
        with trange(total, file=our_file, leave=True, miniters=1,
                    mininterval=0, maxinterval=0) as t:
            with relative_timer() as time_tqdm:
                for i in t:
                    a += i
        assert a == (total * total - total) / 2.0

        a = 0
        with relative_timer() as time_bench:
            for i in _range(total):
                a += i
                our_file.write(("%i" % a) * 40)

    # Compute relative overhead of tqdm against native range()
    try:
        assert time_tqdm() < 60 * time_bench()
    except AssertionError:
        raise AssertionError('trange(%g): %f, range(%g): %f' %
                             (total, time_tqdm(), total, time_bench()))
Esempio n. 9
0
def test_manual_overhead_hard():
    """Test overhead of manual tqdm (hard)"""

    total = int(1e5)

    with closing(MockIO()) as our_file:
        t = tqdm(total=total * 10, file=our_file, leave=True, miniters=1,
                 mininterval=0, maxinterval=0)
        a = 0
        with relative_timer() as time_tqdm:
            for i in _range(total):
                a += i
                t.update(10)

        a = 0
        with relative_timer() as time_bench:
            for i in _range(total):
                a += i
                our_file.write(("%i" % a) * 40)

    # Compute relative overhead of tqdm against native range()
    try:
        assert time_tqdm() < 100 * time_bench()
    except AssertionError:
        raise AssertionError('tqdm(%g): %f, range(%g): %f' %
                             (total, time_tqdm(), total, time_bench()))
Esempio n. 10
0
def test_iter_overhead_simplebar_hard():
    """Test overhead of iteration based tqdm vs simple progress bar (hard)"""

    total = int(1e4)

    with closing(MockIO()) as our_file:
        a = 0
        with trange(total, file=our_file, leave=True, miniters=1,
                    mininterval=0, maxinterval=0) as t:
            with relative_timer() as time_tqdm:
                for i in t:
                    a += i
        assert a == (total * total - total) / 2.0

        a = 0
        s = simple_progress(_range(total), file=our_file, leave=True,
                            miniters=1, mininterval=0)
        with relative_timer() as time_bench:
            for i in s:
                a += i

    # Compute relative overhead of tqdm against native range()
    try:
        assert time_tqdm() < 2.5 * time_bench()
    except AssertionError:
        raise AssertionError('trange(%g): %f, simple_progress(%g): %f' %
                             (total, time_tqdm(), total, time_bench()))
Esempio n. 11
0
def test_manual_overhead_simplebar_hard():
    """Test overhead of manual tqdm vs simple progress bar (hard)"""

    total = int(1e4)

    with closing(MockIO()) as our_file:
        t = tqdm(total=total * 10, file=our_file, leave=True, miniters=1,
                 mininterval=0, maxinterval=0)
        a = 0
        with relative_timer() as time_tqdm:
            for i in _range(total):
                a += i
                t.update(10)

        simplebar_update = simple_progress(
            total=total, file=our_file, leave=True, miniters=1, mininterval=0)
        a = 0
        with relative_timer() as time_bench:
            for i in _range(total):
                a += i
                simplebar_update(10)

    # Compute relative overhead of tqdm against native range()
    try:
        assert time_tqdm() < 2.5 * time_bench()
    except AssertionError:
        raise AssertionError('tqdm(%g): %f, simple_progress(%g): %f' %
                             (total, time_tqdm(), total, time_bench()))
def test_monitoring_and_cleanup():
    """Test for stalled tqdm instance and monitor deletion"""
    # Note: should fix miniters for these tests, else with dynamic_miniters
    # it's too complicated to handle with monitoring update and maxinterval...
    maxinterval = 2

    total = 1000
    # Setup a discrete timer
    timer = DiscreteTimer()
    # And a fake sleeper
    sleeper = FakeSleep(timer)
    # Setup TMonitor to use the timer
    TMonitor._time = timer.time
    TMonitor._event = make_create_fake_sleep_event(sleeper.sleep)
    # Set monitor interval
    tqdm.monitor_interval = maxinterval
    with closing(StringIO()) as our_file:
        with tqdm(total=total, file=our_file, miniters=500, mininterval=0.1,
                  maxinterval=maxinterval) as t:
            cpu_timify(t, timer)
            # Do a lot of iterations in a small timeframe
            # (smaller than monitor interval)
            timer.sleep(maxinterval / 2)  # monitor won't wake up
            t.update(500)
            # check that our fixed miniters is still there
            assert t.miniters == 500
            # Then do 1 it after monitor interval, so that monitor kicks in
            timer.sleep(maxinterval * 2)
            t.update(1)
            # Wait for the monitor to get out of sleep's loop and update tqdm..
            timeend = timer.time()
            while not (t.monitor.woken >= timeend and t.miniters == 1):
                timer.sleep(1)  # Force monitor to wake up if it woken too soon
                sleep(0.000001)  # sleep to allow interrupt (instead of pass)
            assert t.miniters == 1  # check that monitor corrected miniters
            # Note: at this point, there may be a race condition: monitor saved
            # current woken time but timer.sleep() happen just before monitor
            # sleep. To fix that, either sleep here or increase time in a loop
            # to ensure that monitor wakes up at some point.

            # Try again but already at miniters = 1 so nothing will be done
            timer.sleep(maxinterval * 2)
            t.update(2)
            timeend = timer.time()
            while t.monitor.woken < timeend:
                timer.sleep(1)  # Force monitor to wake up if it woken too soon
                sleep(0.000001)
            # Wait for the monitor to get out of sleep's loop and update tqdm..
            assert t.miniters == 1  # check that monitor corrected miniters

    # Check that class var monitor is deleted if no instance left
    tqdm.monitor_interval = 10
    assert tqdm.monitor is None
Esempio n. 13
0
def test_pandas_setup():
    """Test tqdm.pandas()"""
    try:
        from numpy.random import randint
        import pandas as pd
    except ImportError:
        raise SkipTest

    with closing(StringIO()) as our_file:
        tqdm.pandas(file=our_file, leave=True, ascii=True, total=123)
        series = pd.Series(randint(0, 50, (100,)))
        series.progress_apply(lambda x: x + 10)
        res = our_file.getvalue()
        assert '100/123' in res
Esempio n. 14
0
def test_pandas_deprecation():
    """Test bar object instance as argument deprecation"""
    try:
        from numpy.random import randint
        from tqdm import tqdm_pandas
        import pandas as pd
    except ImportError:
        raise SkipTest

    with closing(StringIO()) as our_file:
        tqdm_pandas(tqdm(file=our_file, leave=False, ascii=True, ncols=20))
        df = pd.DataFrame(randint(0, 50, (500, 3)))
        df.groupby(0).progress_apply(lambda x: None)
        # Check deprecation message
        assert "TqdmDeprecationWarning" in our_file.getvalue()
        assert "instead of `tqdm_pandas(tqdm(...))`" in our_file.getvalue()

    with closing(StringIO()) as our_file:
        tqdm_pandas(tqdm, file=our_file, leave=False, ascii=True, ncols=20)
        df = pd.DataFrame(randint(0, 50, (500, 3)))
        df.groupby(0).progress_apply(lambda x: None)
        # Check deprecation message
        assert "TqdmDeprecationWarning" in our_file.getvalue()
        assert "instead of `tqdm_pandas(tqdm, ...)`" in our_file.getvalue()
Esempio n. 15
0
def test_pandas_map():
    """ Test pandas.Series.progress_map """
    try:
        from numpy.random import randint
        import pandas as pd
    except:
        raise SkipTest

    with closing(StringIO()) as our_file:
        tqdm.pandas(file=our_file, leave=True, ascii=True)
        dfs = pd.DataFrame(randint(0, 50, (500, 3)), columns=list("abc"))
        dfs.a.progress_map(lambda x: None)

        if our_file.getvalue().count("100%") < 1:
            raise AssertionError("\nExpected:\n{0}\nIn:{1}\n".format("100% at least twice", our_file.getvalue()))
def test_monitoring_multi():
    """Test on multiple bars, one not needing miniters adjustment"""
    # Note: should fix miniters for these tests, else with dynamic_miniters
    # it's too complicated to handle with monitoring update and maxinterval...
    maxinterval = 2

    total = 1000
    # Setup a discrete timer
    timer = DiscreteTimer()
    # And a fake sleeper
    sleeper = FakeSleep(timer)
    # Setup TMonitor to use the timer
    TMonitor._time = timer.time
    TMonitor._event = make_create_fake_sleep_event(sleeper.sleep)
    # Set monitor interval
    tqdm.monitor_interval = maxinterval
    with closing(StringIO()) as our_file:
        with tqdm(total=total, file=our_file, miniters=500, mininterval=0.1,
                  maxinterval=maxinterval) as t1:
            # Set high maxinterval for t2 so monitor does not need to adjust it
            with tqdm(total=total, file=our_file, miniters=500, mininterval=0.1,
                      maxinterval=1E5) as t2:
                cpu_timify(t1, timer)
                cpu_timify(t2, timer)
                # Do a lot of iterations in a small timeframe
                timer.sleep(maxinterval / 2)
                t1.update(500)
                t2.update(500)
                assert t1.miniters == 500
                assert t2.miniters == 500
                # Then do 1 it after monitor interval, so that monitor kicks in
                timer.sleep(maxinterval * 2)
                t1.update(1)
                t2.update(1)
                # Wait for the monitor to get out of sleep and update tqdm
                timeend = timer.time()
                while not (t1.monitor.woken >= timeend and t1.miniters == 1):
                    timer.sleep(1)
                    sleep(0.000001)
                assert t1.miniters == 1  # check that monitor corrected miniters
                assert t2.miniters == 500  # check that t2 was not adjusted

    # Check that class var monitor is deleted if no instance left
    tqdm.monitor_interval = 10
    assert tqdm.monitor is None
Esempio n. 17
0
def test_pandas_leave():
    """ Test pandas with `leave=True` """
    try:
        from numpy.random import randint
        import pandas as pd
    except:
        raise SkipTest

    with closing(StringIO()) as our_file:
        df = pd.DataFrame(randint(0, 100, (1000, 6)))
        tqdm.pandas(file=our_file, leave=True, ascii=True)
        df.groupby(0).progress_apply(lambda x: None)

        our_file.seek(0)

        exres = "100%|##########| 101/101"
        if exres not in our_file.read():
            our_file.seek(0)
            raise AssertionError("\nExpected:\n{0}\nIn:{1}\n".format(exres, our_file.read()))
Esempio n. 18
0
def test_pandas_apply_args_deprecation():
    """Test warning info in
    `pandas.Dataframe(Series).progress_apply(func, *args)`"""
    try:
        from numpy.random import randint
        from tqdm import tqdm_pandas
        import pandas as pd
    except ImportError:
        raise SkipTest

    with closing(StringIO()) as our_file:
        tqdm_pandas(tqdm(file=our_file, leave=False, ascii=True, ncols=20))
        df = pd.DataFrame(randint(0, 50, (500, 3)))
        df.progress_apply(lambda x: None, 1)  # 1 shall cause a warning
        # Check deprecation message
        res = our_file.getvalue()
        assert all([i in res for i in (
            "TqdmDeprecationWarning", "not supported",
            "keyword arguments instead")])
Esempio n. 19
0
def test_pandas_data_frame():
    """Test pandas.DataFrame.progress_apply and .progress_applymap"""
    try:
        from numpy.random import randint
        import pandas as pd
    except ImportError:
        raise SkipTest

    with closing(StringIO()) as our_file:
        tqdm.pandas(file=our_file, leave=True, ascii=True)
        df = pd.DataFrame(randint(0, 50, (100, 200)))

        def task_func(x):
            return x + 1

        # applymap
        res1 = df.progress_applymap(task_func)
        res2 = df.applymap(task_func)
        assert res1.equals(res2)

        # apply
        for axis in [0, 1, 'index', 'columns']:
            res3 = df.progress_apply(task_func, axis=axis)
            res4 = df.apply(task_func, axis=axis)
            assert res3.equals(res4)

        our_file.seek(0)
        if our_file.read().count('100%') < 3:
            our_file.seek(0)
            raise AssertionError("\nExpected:\n{0}\nIn:\n{1}\n".format(
                '100% at least three times', our_file.read()))

        # apply_map, apply axis=0, apply axis=1
        expects = ['20000/20000', '200/200', '100/100']
        for exres in expects:
            our_file.seek(0)
            if our_file.getvalue().count(exres) < 1:
                our_file.seek(0)
                raise AssertionError(
                    "\nExpected:\n{0}\nIn:\n {1}\n".format(
                        exres + " at least once.", our_file.read()))
Esempio n. 20
0
def test_pandas_apply():
    """ Test pandas.DataFrame[.series].progress_apply """
    try:
        from numpy.random import randint
        import pandas as pd
    except:
        raise SkipTest

    with closing(StringIO()) as our_file:
        tqdm.pandas(file=our_file, leave=True, ascii=True)
        df = pd.DataFrame(randint(0, 50, (500, 3)))
        df.progress_apply(lambda x: None)

        dfs = pd.DataFrame(randint(0, 50, (500, 3)),
                           columns=list('abc'))
        dfs.a.progress_apply(lambda x: None)

        our_file.seek(0)

        if our_file.read().count('100%') < 2:
            our_file.seek(0)
            raise AssertionError("\nExpected:\n{0}\nIn:{1}\n".format(
                '100% at least twice', our_file.read()))
Esempio n. 21
0
def test_main():
    """ Test command line pipes """
    ls_out = _sh("ls").replace("\r\n", "\n")
    ls = subprocess.Popen(("ls"), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    res = _sh(sys.executable, "-c", "from tqdm import main; main()", stdin=ls.stdout, stderr=subprocess.STDOUT)
    ls.wait()

    # actual test:

    assert ls_out in res.replace("\r\n", "\n")

    # semi-fake test which gets coverage:
    try:
        _SYS = (deepcopy(sys.stdin), deepcopy(sys.argv))
    except:
        pass

    with closing(UnicodeIO()) as sys.stdin:
        sys.argv = ["", "--desc", "Test CLI delims", "--ascii", "True", "--delim", r"\0", "--buf_size", "64"]
        sys.stdin.write("\0".join(map(str, _range(int(1e3)))))
        sys.stdin.seek(0)
        main()

    sys.stdin = map(str, _range(int(1e3)))
    sys.argv = ["", "--desc", "Test CLI pipes", "--ascii", "True", "--unit_scale", "True"]
    import tqdm.__main__  # NOQA

    sys.argv = ["", "-ascii", "--unit_scale", "False", "--desc", "Test CLI errors"]
    main()

    sys.argv = ["", "-ascii", "-unit_scale", "--bad_arg_u_ment", "foo"]
    try:
        main()
    except TqdmKeyError as e:
        if "bad_arg_u_ment" not in str(e):
            raise
    else:
        raise TqdmKeyError("bad_arg_u_ment")

    sys.argv = ["", "-ascii", "-unit_scale", "invalid_bool_value"]
    try:
        main()
    except TqdmTypeError as e:
        if "invalid_bool_value" not in str(e):
            raise
    else:
        raise TqdmTypeError("invalid_bool_value")

    sys.argv = ["", "-ascii", "--total", "invalid_int_value"]
    try:
        main()
    except TqdmTypeError as e:
        if "invalid_int_value" not in str(e):
            raise
    else:
        raise TqdmTypeError("invalid_int_value")

    for i in ("-h", "--help", "-v", "--version"):
        sys.argv = ["", i]
        try:
            main()
        except SystemExit:
            pass

    # clean up
    try:
        sys.stdin, sys.argv = _SYS
    except:
        pass
Esempio n. 22
0
def test_main():
    """ Test command line pipes """
    ls_out = _sh('ls').replace('\r\n', '\n')
    ls = subprocess.Popen(('ls'),
                          stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT)
    res = _sh('python', '-c', 'from tqdm import main; main()',
              stdin=ls.stdout,
              stderr=subprocess.STDOUT)
    ls.wait()

    # actual test:

    assert (ls_out in res.replace('\r\n', '\n'))

    # semi-fake test which gets coverage:
    try:
        _SYS = (deepcopy(sys.stdin), deepcopy(sys.argv))
    except:
        pass

    with closing(UnicodeIO()) as sys.stdin:
        sys.argv = ['', '--desc', 'Test CLI delims',
                    '--ascii', 'True', '--delim', r'\0', '--buf_size', '64']
        sys.stdin.write('\0'.join(map(str, _range(int(1e3)))))
        sys.stdin.seek(0)
        main()

    sys.stdin = map(str, _range(int(1e3)))
    sys.argv = ['', '--desc', 'Test CLI pipes',
                '--ascii', 'True', '--unit_scale', 'True']
    import tqdm.__main__  # NOQA

    sys.argv = ['', '-ascii', '--unit_scale', 'False',
                '--desc', 'Test CLI errors']
    main()

    sys.argv = ['', '-ascii', '-unit_scale', '--bad_arg_u_ment', 'foo']
    try:
        main()
    except TqdmKeyError as e:
        if 'bad_arg_u_ment' not in str(e):
            raise
    else:
        raise TqdmKeyError('bad_arg_u_ment')

    sys.argv = ['', '-ascii', '-unit_scale', 'invalid_bool_value']
    try:
        main()
    except TqdmTypeError as e:
        if 'invalid_bool_value' not in str(e):
            raise
    else:
        raise TqdmTypeError('invalid_bool_value')

    sys.argv = ['', '-ascii', '--total', 'invalid_int_value']
    try:
        main()
    except TqdmTypeError as e:
        if 'invalid_int_value' not in str(e):
            raise
    else:
        raise TqdmTypeError('invalid_int_value')

    for i in ('-h', '--help', '-v', '--version'):
        sys.argv = ['', i]
        try:
            main()
        except SystemExit:
            pass

    # clean up
    try:
        sys.stdin, sys.argv = _SYS
    except:
        pass
Esempio n. 23
0
def test_main():
    """Test command line pipes"""
    ls_out = _sh('ls').replace('\r\n', '\n')
    ls = subprocess.Popen('ls', stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT)
    res = _sh(sys.executable, '-c', 'from tqdm import main; main()',
              stdin=ls.stdout, stderr=subprocess.STDOUT)
    ls.wait()

    # actual test:

    assert ls_out in res.replace('\r\n', '\n')

    # semi-fake test which gets coverage:
    _SYS = sys.stdin, sys.argv

    with closing(StringIO()) as sys.stdin:
        sys.argv = ['', '--desc', 'Test CLI-delims',
                    '--ascii', 'True', '--delim', r'\0', '--buf_size', '64']
        sys.stdin.write('\0'.join(map(str, _range(int(1e3)))))
        sys.stdin.seek(0)
        main()

    IN_DATA_LIST = map(str, _range(int(1e3)))
    sys.stdin = IN_DATA_LIST
    sys.argv = ['', '--desc', 'Test CLI pipes',
                '--ascii', 'True', '--unit_scale', 'True']
    import tqdm.__main__  # NOQA

    IN_DATA = '\0'.join(IN_DATA_LIST)
    with closing(StringIO()) as sys.stdin:
        sys.stdin.write(IN_DATA)
        sys.stdin.seek(0)
        sys.argv = ['', '--ascii', '--bytes', '--unit_scale', 'False']
        with closing(UnicodeIO()) as fp:
            main(fp=fp)
            assert str(len(IN_DATA)) in fp.getvalue()

    sys.stdin = IN_DATA_LIST
    sys.argv = ['', '-ascii', '--unit_scale', 'False',
                '--desc', 'Test CLI errors']
    main()

    sys.argv = ['', '-ascii', '-unit_scale', '--bad_arg_u_ment', 'foo']
    try:
        main()
    except TqdmKeyError as e:
        if 'bad_arg_u_ment' not in str(e):
            raise
    else:
        raise TqdmKeyError('bad_arg_u_ment')

    sys.argv = ['', '-ascii', '-unit_scale', 'invalid_bool_value']
    try:
        main()
    except TqdmTypeError as e:
        if 'invalid_bool_value' not in str(e):
            raise
    else:
        raise TqdmTypeError('invalid_bool_value')

    sys.argv = ['', '-ascii', '--total', 'invalid_int_value']
    try:
        main()
    except TqdmTypeError as e:
        if 'invalid_int_value' not in str(e):
            raise
    else:
        raise TqdmTypeError('invalid_int_value')

    # test SystemExits
    for i in ('-h', '--help', '-v', '--version'):
        sys.argv = ['', i]
        try:
            main()
        except SystemExit:
            pass

    # test --manpath
    tmp = mkdtemp()
    man = path.join(tmp, "tqdm.1")
    assert not path.exists(man)
    try:
        main(argv=['--manpath', tmp])
    except SystemExit:
        pass
    else:
        raise SystemExit("Expected system exit")
    assert path.exists(man)
    rmtree(tmp, True)

    # test --log
    with closing(StringIO()) as sys.stdin:
        sys.stdin.write('\0'.join(map(str, _range(int(1e3)))))
        sys.stdin.seek(0)
        # with closing(UnicodeIO()) as fp:
        main(argv=['--log', 'DEBUG'])
        # assert "DEBUG:" in sys.stdout.getvalue()

    # clean up
    sys.stdin, sys.argv = _SYS
Esempio n. 24
0
def test_main():
    """Test command line pipes"""
    ls_out = _sh('ls').replace('\r\n', '\n')
    ls = subprocess.Popen('ls',
                          stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT)
    res = _sh(sys.executable,
              '-c',
              'from tqdm import main; main()',
              stdin=ls.stdout,
              stderr=subprocess.STDOUT)
    ls.wait()

    # actual test:

    assert (ls_out in res.replace('\r\n', '\n'))

    # semi-fake test which gets coverage:
    _SYS = sys.stdin, sys.argv

    with closing(StringIO()) as sys.stdin:
        sys.argv = [
            '', '--desc', 'Test CLI-delims', '--ascii', 'True', '--delim',
            r'\0', '--buf_size', '64'
        ]
        sys.stdin.write('\0'.join(map(str, _range(int(1e3)))))
        sys.stdin.seek(0)
        main()

    IN_DATA_LIST = map(str, _range(int(1e3)))
    sys.stdin = IN_DATA_LIST
    sys.argv = [
        '', '--desc', 'Test CLI pipes', '--ascii', 'True', '--unit_scale',
        'True'
    ]
    import tqdm.__main__  # NOQA

    IN_DATA = '\0'.join(IN_DATA_LIST)
    with closing(StringIO()) as sys.stdin:
        sys.stdin.write(IN_DATA)
        sys.stdin.seek(0)
        sys.argv = ['', '--ascii', '--bytes', '--unit_scale', 'False']
        with closing(UnicodeIO()) as fp:
            main(fp=fp)
            assert (str(len(IN_DATA)) in fp.getvalue())

    sys.stdin = IN_DATA_LIST
    sys.argv = [
        '', '-ascii', '--unit_scale', 'False', '--desc', 'Test CLI errors'
    ]
    main()

    sys.argv = ['', '-ascii', '-unit_scale', '--bad_arg_u_ment', 'foo']
    try:
        main()
    except TqdmKeyError as e:
        if 'bad_arg_u_ment' not in str(e):
            raise
    else:
        raise TqdmKeyError('bad_arg_u_ment')

    sys.argv = ['', '-ascii', '-unit_scale', 'invalid_bool_value']
    try:
        main()
    except TqdmTypeError as e:
        if 'invalid_bool_value' not in str(e):
            raise
    else:
        raise TqdmTypeError('invalid_bool_value')

    sys.argv = ['', '-ascii', '--total', 'invalid_int_value']
    try:
        main()
    except TqdmTypeError as e:
        if 'invalid_int_value' not in str(e):
            raise
    else:
        raise TqdmTypeError('invalid_int_value')

    for i in ('-h', '--help', '-v', '--version'):
        sys.argv = ['', i]
        try:
            main()
        except SystemExit:
            pass

    # clean up
    sys.stdin, sys.argv = _SYS