Exemplo n.º 1
0
def tcl_interp():
    """
    create a new Tcl interpreter with the standard packages loaded

    TESTS::

        sage: from yacop.utils.tcl import tcl_interp, tcl_eval
        sage: tcl = tcl_interp()
        sage: tcl.eval("package present sqlite3") # random
        3.8.2
    """
    tcl = Tcl()
    xdirs = Yacop.tcllibrary
    if not xdirs is None:
        if not isinstance(xdirs, list):
            xdirs = [xdirs]
            [tcl.eval("lappend auto_path {%s}" % path) for path in xdirs]
    tcl.eval(
        """
        lappend auto_path $::env(SAGE_LOCAL)/tcl/lib
        lappend auto_path $::env(SAGE_LOCAL)/lib
        package require yacop::sage 1.0
            """
    )
    return tcl
Exemplo n.º 2
0
def get_tk_patchlevel():
    global _tk_patchlevel
    if _tk_patchlevel is None:
        tcl = Tcl()
        patchlevel = []
        for x in tcl.call('info', 'patchlevel').split('.'):
            try:
                x = int(x, 10)
            except ValueError:
                x = -1
            patchlevel.append(x)
        _tk_patchlevel = tuple(patchlevel)
    return _tk_patchlevel
Exemplo n.º 3
0
def get_tk_patchlevel():
    global _tk_patchlevel
    if _tk_patchlevel is None:
        tcl = Tcl()
        patchlevel = []
        for x in tcl.call('info', 'patchlevel').split('.'):
            try:
                x = int(x, 10)
            except ValueError:
                x = -1
            patchlevel.append(x)
        _tk_patchlevel = tuple(patchlevel)
    return _tk_patchlevel
Exemplo n.º 4
0
def get_tk_patchlevel():
    global _tk_patchlevel
    if _tk_patchlevel is None:
        tcl = Tcl()
        patchlevel = tcl.call('info', 'patchlevel')
        m = re.fullmatch(r'(\d+)\.(\d+)([ab.])(\d+)', patchlevel)
        major, minor, releaselevel, serial = m.groups()
        major, minor, serial = int(major), int(minor), int(serial)
        releaselevel = {'a': 'alpha', 'b': 'beta', '.': 'final'}[releaselevel]
        if releaselevel == 'final':
            _tk_patchlevel = major, minor, serial, releaselevel, 0
        else:
            _tk_patchlevel = major, minor, 0, releaselevel, serial
    return _tk_patchlevel
Exemplo n.º 5
0
def get_tk_patchlevel():
    global _tk_patchlevel
    if _tk_patchlevel is None:
        tcl = Tcl()
        patchlevel = tcl.call('info', 'patchlevel')
        m = re.fullmatch(r'(\d+)\.(\d+)([ab.])(\d+)', patchlevel)
        major, minor, releaselevel, serial = m.groups()
        major, minor, serial = int(major), int(minor), int(serial)
        releaselevel = {'a': 'alpha', 'b': 'beta', '.': 'final'}[releaselevel]
        if releaselevel == 'final':
            _tk_patchlevel = major, minor, serial, releaselevel, 0
        else:
            _tk_patchlevel = major, minor, 0, releaselevel, serial
    return _tk_patchlevel
Exemplo n.º 6
0
    def __init__(self, sim_dir, fn_root, **kwargs):
        rms = kwargs.get('rms', False)
        down = kwargs.get('downsample', 1)
        self.sim_dir = sim_dir
        datp_dir = os.path.join(sim_dir, 'datp')
        rotation = kwargs.get('rotation', 0)
        self.rot = rotation / 180 * np.pi
        self.length_scale = kwargs.get('length_scale', 96)
        # Find what you're looking for
        fns = [fn for fn in os.listdir(datp_dir) if fn.startswith(fn_root) and fn.endswith('.pvti')]
        # Sort files
        fns = Tcl().call('lsort', '-dict', fns)

        if len(fns) > 1:
            print("More than one fn with this name. Taking time average.")
            # Store snapshots of field
            self.snaps = []
            for fn in fns[::down]:
                snap = vti_to_mesh(os.path.join(datp_dir, fn), self.length_scale)
                self.snaps.append(snap)
            del snap
            # Time average the flow field snaps
            mean_t = np.mean(np.array(self.snaps).T, axis=1)
            self.X, self.Y = mean_t[0:2]
            self.u, self.v, self.w = mean_t[2:-1]
            self.U, self.V = np.mean(self.u, axis=2), np.mean(self.v, axis=2)
            self.p = np.mean(mean_t[-1], axis=0)
            del mean_t
        else:
            # assert (len(fns) > 0), 'You dont have '+fn_root+'.pvtr in your datp folder'
            self.X, self.Y, self.U, self.V, self.W, self.p = vti_to_mesh(os.path.join(datp_dir, fns[0]),
                                                                         self.length_scale)
            self.U, self.V = np.squeeze(self.U), np.squeeze(self.V)
            self.p = np.squeeze(self.p)
Exemplo n.º 7
0
    def __init__(self, path, img_size=640):
        p = str(Path(path))  # os-agnostic
        p = os.path.abspath(p)  # absolute path
        if '*' in p:
            files = sorted(glob.glob(p, recursive=True))  # glob
        elif os.path.isdir(p):
            files = Tcl().call('lsort', '-dict',
                               glob.glob(os.path.join(p, '*.*')))

        elif os.path.isfile(p):
            files = [p]  # files
        else:
            raise Exception('ERROR: %s does not exist' % p)

        images = [x for x in files if x.split('.')[-1].lower() in img_formats]
        videos = [x for x in files if x.split('.')[-1].lower() in vid_formats]
        ni, nv = len(images), len(videos)

        self.img_size = img_size
        self.files = images + videos
        self.nf = ni + nv  # number of files
        self.video_flag = [False] * ni + [True] * nv
        self.mode = 'images'
        if any(videos):
            self.new_video(videos[0])  # new video
        else:
            self.cap = None
        assert self.nf > 0, 'No images or videos found in %s. Supported formats are:\nimages: %s\nvideos: %s' % \
                            (p, img_formats, vid_formats)
Exemplo n.º 8
0
def hook_tkinter(finder, module):
    """Recusively copy tcl and tk directories"""
    from tkinter import Tcl
    from _tkinter import TK_VERSION
    tcl_dir = os.path.normpath(Tcl().eval("info library"))
    assert os.path.isdir(tcl_dir)
    finder.add_datadirectory("lib/tcl", tcl_dir, recursive=True)
    tk_dir = os.path.join(os.path.dirname(tcl_dir), 'tk{}'.format(TK_VERSION))
    assert os.path.isdir(tk_dir)
    finder.add_datadirectory("lib/tk", tk_dir, recursive=True)
    finder.set_min_bundle("tkinter", 2)
    if sys.version_info >= (3, 6, 0):
        finder.import_hook("imp")
    # import DLLs
    tk_ver = TK_VERSION.replace('.', '')
    import glob
    for dll_search in ["tcl" + tk_ver + "*.dll", "tk" + tk_ver + "*.dll"]:
        for dll_path in glob.glob(
                os.path.join(sys.base_prefix, "DLLs", dll_search)):
            dll_name = os.path.basename(dll_path)
            finder.add_dll(dll_path)
    # add environment variables that point to the copied paths at runtime
    finder.add_bootcode("""
def tk_env_paths():
    import os
    tcl_dir = os.path.join(os.getcwd(), 'lib', 'tcl')
    tk_dir = os.path.join(os.getcwd(), 'lib', 'tk')
    os.environ["TCL_LIBRARY"] = tcl_dir
    os.environ["TK_LIBRARY"] = tk_dir

tk_env_paths()
del tk_env_paths
""")
Exemplo n.º 9
0
def hook_tkinter(finder, module):
    """Recusively copy tcl and tk directories"""
    from tkinter import Tcl
    from _tkinter import TK_VERSION
    tcl_dir = os.path.normpath(Tcl().eval("info library"))
    assert os.path.isdir(tcl_dir)
    finder.add_datadirectory("lib/tcl", tcl_dir, recursive=True)
    tk_dir = os.path.join(os.path.dirname(tcl_dir), 'tk{}'.format(TK_VERSION))
    assert os.path.isdir(tk_dir)
    finder.add_datadirectory("lib/tk", tk_dir, recursive=True)
    if sys.version_info >= (3, 6, 0):
        finder.import_hook("imp")

    # add environment variables that point to the copied paths at runtime
    finder.add_bootcode("""
def tk_env_paths():
    import os
    import sys
    import _tkinter
    basepath = os.path.dirname(sys.executable)
    tcl_dir = os.path.join(basepath, 'lib', 'tcl')
    tk_dir = os.path.join(basepath, 'lib', 'tk')
    os.environ["TCL_LIBRARY"] = tcl_dir
    os.environ["TK_LIBRARY"] = tk_dir

tk_env_paths()
del tk_env_paths
""")
Exemplo n.º 10
0
class TgnTk:
    """Native Python Tk interpreter."""

    def __init__(self) -> None:
        """Init Tcl object."""
        self.tcl = Tcl()

    def eval(self, command: str) -> str:  # noqa: A003
        """Execute Tcl eval command."""
        return self.tcl.eval(command)
Exemplo n.º 11
0
def get_nlast_images(nb_images):
    imgs_list_full_dir = f"{ROOT_DIR}/_tmp/full/"
    os.chdir(imgs_list_full_dir)

    images_taken = glob.glob('*.JPG')
    images_taken.extend(glob.glob('*.jpeg'))
    images_taken.extend(glob.glob('*.jpg'))
    images_taken_sorted = Tcl().call('lsort', '-dict', images_taken)

    return images_taken_sorted if nb_images == -1 else images_taken_sorted[-nb_images:]
Exemplo n.º 12
0
 def testLoadTk(self):
     import os
     if 'DISPLAY' not in os.environ:
         # skipping test of clean upgradeability
         return
     tcl = Tcl()
     self.assertRaises(TclError, tcl.winfo_geometry)
     tcl.loadtk()
     self.assertEqual('1x1+0+0', tcl.winfo_geometry())
     tcl.destroy()
Exemplo n.º 13
0
    def _init_tcl(self):
        """Initialize Tcl interpreter.

        Returns:
            None

        """
        try:
            self.Tcl is None
        except AttributeError:
            self.Tcl = Tcl()

            # Define logger
            def tcl_puts(*args):
                """Enables logging for tcl output.

                Returns:
                    None

                """
                if len(args) >= 2:
                    stream = args[0]
                    if stream == "stdout":
                        self.class_logger.debug(" ".join(args[1:]))
                    elif stream == "stderr":
                        self.class_logger.error(" ".join(args[1:]))
                    else:
                        self.class_logger.debug("stream <%s>: %s" %
                                                (args[0], " ".join(args[1:])))
                elif len(args) == 1:
                    self.class_logger.debug(args[0])
                else:
                    self.class_logger.error("Called puts without arguments.")
                return None

            self.Tcl.createcommand("tcl_puts", tcl_puts)
            self.class_logger.debug("Insert tcl script to catch puts output.")
            ixia_helpers.tcl_puts_replace(self.Tcl)

            ixia_helpers.ixtclhal_import(self.Tcl)
Exemplo n.º 14
0
 def testLoadTkFailure(self):
     old_display = None
     if sys.platform.startswith(('win', 'darwin', 'cygwin')):
         return
     with test_support.EnvironmentVarGuard() as env:
         if 'DISPLAY' in os.environ:
             del env['DISPLAY']
             with os.popen('echo $DISPLAY') as pipe:
                 display = pipe.read().strip()
             if display:
                 return
         tcl = Tcl()
         self.assertRaises(TclError, tcl.winfo_geometry)
         self.assertRaises(TclError, tcl.loadtk)
Exemplo n.º 15
0
def cards():
    path = f"{ROOT_DIR}/_tmp/cards"
    os.chdir(path)

    images_taken = glob.glob('*.JPG')
    images_taken.extend(glob.glob('*.jpeg'))
    images_taken.extend(glob.glob('*.jpg'))

    images_taken_sorted = Tcl().call('lsort', '-dict', images_taken)
    images_taken_sorted = list(reversed(images_taken_sorted))

    return render_template('cards.html',
                           images_list=images_taken_sorted,
                           classes=generate_grid_classes(
                               len(images_taken_sorted)))
Exemplo n.º 16
0
 def animate(self, folder, **kwargs):
     for idx, snap in enumerate(self.snaps):
         dat = np.array(snap).T
         plot_2D_fp_isocontours(dat, 'mag', folder + str(idx) + '.png',
                                **kwargs)
     # Sort filenames to make sure they're in order
     fn_images = os.listdir(folder)
     fn_images = Tcl().call('lsort', '-dict', fn_images)
     images = []
     for filename in fn_images:
         images.append(imageio.imread(os.path.join(folder, filename)))
     imageio.mimsave(folder + '/flow.gif',
                     images,
                     duration=0.2,
                     bitrate=1000)
Exemplo n.º 17
0
 def testLoadTk(self):
     import os
     if 'DISPLAY' not in os.environ:
         # skipping test of clean upgradeability
         return
     tcl = Tcl()
     self.assertRaises(TclError,tcl.winfo_geometry)
     tcl.loadtk()
     self.assertEqual('1x1+0+0', tcl.winfo_geometry())
     tcl.destroy()
Exemplo n.º 18
0
    def __init__(self, sim_dir, fn_root, **kwargs):
        rms = kwargs.get('rms', False)
        down = kwargs.get('downsample', 1)
        self.sim_dir = sim_dir
        datp_dir = os.path.join(sim_dir, 'datp')
        rotation = kwargs.get('rotation', 0)
        self.rot = 0
        self.length_scale = kwargs.get('length_scale', 96)
        # Find what you're looking for
        fns = [
            fn for fn in os.listdir(datp_dir)
            if fn.startswith(fn_root) and fn.endswith('.pvtr')
        ]
        # Sort files
        fns = Tcl().call('lsort', '-dict', fns)

        if len(fns) > 1:
            print("More than one fn with this name. Taking time average.")
            # Store snapshots of field
            self.snaps = []
            for fn in fns[::down]:
                snap = vtr_to_mesh(os.path.join(datp_dir, fn),
                                   self.length_scale)
                self.snaps.append(snap)
            del snap
            # Time average the flow field snaps
            mean_t = np.mean(np.array(self.snaps).T, axis=1)
            self.X, self.Y = mean_t[0:2]
            self.u, self.v, self.w = mean_t[2:-1]
            self.U, self.V = np.mean(self.u, axis=2), np.mean(self.v, axis=2)
            self.p = np.mean(mean_t[-1], axis=0)
            del mean_t
        else:
            assert (len(fns) > 0
                    ), 'You dont have ' + fn_root + '.pvtr in your datp folder'
            self.X, self.Y, self.U, self.V, self.W, self.p = vtr_to_mesh(
                os.path.join(datp_dir, fns[0]), self.length_scale)
            self.U, self.V = np.squeeze(self.U), np.squeeze(self.V)
            self.p = np.squeeze(self.p)
        self.z = np.ones(np.shape(self.X))
        # --- Unpack mean flow quantities ---
        names = kwargs.get('names', [
            't', 'dt', 'px', 'py', 'pz', 'vx', 'vy', 'vz', 'v2x', 'v2y', 'v2z'
        ])
        fos = (io.unpack_flex_forces(os.path.join(self.sim_dir, 'fort.9'),
                                     names))
        self.fos = dict(zip(names, fos))
Exemplo n.º 19
0
def generate_corpus(txt_dirs):

    for txt_dir in txt_dirs:

        corpus_full_path = txt_dir + '/corpus.txt'

        if path.exists(corpus_full_path):
            print('Corpus exists, returning...')
            continue

        with open(corpus_full_path, 'w+') as corpus:
            # Need to preserve order
            for file in Tcl().call('lsort', '-dict', os.listdir(txt_dir)):
                full_path = txt_dir + '/' + file
                with open(full_path, 'r') as source:
                    corpus.write(source.read())
                corpus.write(' ')
Exemplo n.º 20
0
def create_txt(set, ids):
    path = os.path.join('datasets', args.project)
    os.makedirs(path, exist_ok=True)

    with open(os.path.join(path, f'{set}.txt'), 'w') as f:
        for label, id in enumerate(ids):
            if (val_size == 0) and (set == 'val'):
                break

            images = os.listdir(os.path.join(root, id))
            images = Tcl().call('lsort', '-dict', images)  # sort

            if val_size != 0:
                if set == 'train':
                    images = images[:-val_size]
                elif set == 'val':
                    images = images[-val_size:]

            for image in images:
                f.write(f'{id}/{image} {label}\n')

    return print(f'------{set}.txt created------')
Exemplo n.º 21
0
    def testLoadTkFailure(self):
        old_display = None
        if sys.platform.startswith(('win', 'darwin', 'cygwin')):
            # no failure possible on windows?

            # XXX Maybe on tk older than 8.4.13 it would be possible,
            # see tkinter.h.
            return
        with test_support.EnvironmentVarGuard() as env:
            if 'DISPLAY' in os.environ:
                del env['DISPLAY']
                # on some platforms, deleting environment variables
                # doesn't actually carry through to the process level
                # because they don't support unsetenv
                # If that's the case, abort.
                display = os.popen('echo $DISPLAY').read().strip()
                if display:
                    return

            tcl = Tcl()
            self.assertRaises(TclError, tcl.winfo_geometry)
            self.assertRaises(TclError, tcl.loadtk)
Exemplo n.º 22
0
 def testLoadTkFailure(self):
     import os
     old_display = None
     import sys
     if sys.platform.startswith(('win', 'darwin', 'cygwin')):
         return  # no failure possible on windows?
     if 'DISPLAY' in os.environ:
         old_display = os.environ['DISPLAY']
         del os.environ['DISPLAY']
         # on some platforms, deleting environment variables
         # doesn't actually carry through to the process level
         # because they don't support unsetenv
         # If that's the case, abort.
         display = os.popen('echo $DISPLAY').read().strip()
         if display:
             return
     try:
         tcl = Tcl()
         self.assertRaises(TclError, tcl.winfo_geometry)
         self.assertRaises(TclError, tcl.loadtk)
     finally:
         if old_display is not None:
             os.environ['DISPLAY'] = old_display
Exemplo n.º 23
0
    def __check_enviroment(self):
        try:
            self.py_Version = platform.python_version()
            self.py_Compiler = platform.python_compiler()
            self.py_Build = platform.python_build()

            major, minor, patch = self.py_Version.split(".")
            if (int(major) < MIN_PY_MAJOR_VERSION) or (
                (int(major) == MIN_PY_MAJOR_VERSION) and (int(minor) < MIN_PY_MINOR_VERSION)
            ):
                raise Exception(
                    "Python Version " + MIN_TCL_MAJOR_VERSION + "." + MIN_TCL_MINOR_VERSION + ".x or higher required"
                )

            self.tcl_Version = Tcl().eval("info patchlevel")
            major, minor, patch = self.tcl_Version.split(".")
            if (int(major) < MIN_TCL_MAJOR_VERSION) or (
                (int(major) == MIN_TCL_MAJOR_VERSION) and (int(minor) < MIN_TCL_MINOR_VERSION)
            ):
                raise Exception(
                    "TCL Version " + MIN_TCL_MAJOR_VERSION + "." + MIN_TCL_MINOR_VERSION + ".x or higher required"
                )
        except:
            raise
Exemplo n.º 24
0
class TclTest(unittest.TestCase):
    def setUp(self):
        self.interp = Tcl()
        self.wantobjects = self.interp.tk.wantobjects()

    def testEval(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.eval('set a'), '1')

    def test_eval_null_in_result(self):
        tcl = self.interp
        self.assertEqual(tcl.eval('set a "a\\0b"'), 'a\x00b')

    def test_eval_surrogates_in_result(self):
        tcl = self.interp
        self.assertIn(tcl.eval(r'set a "<\ud83d\udcbb>"'), '<\U0001f4bb>')

    def testEvalException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.eval, 'set a')

    def testEvalException2(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.eval, 'this is wrong')

    def testCall(self):
        tcl = self.interp
        tcl.call('set', 'a', '1')
        self.assertEqual(tcl.call('set', 'a'), '1')

    def testCallException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.call, 'set', 'a')

    def testCallException2(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.call, 'this', 'is', 'wrong')

    def testSetVar(self):
        tcl = self.interp
        tcl.setvar('a', '1')
        self.assertEqual(tcl.eval('set a'), '1')

    def testSetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)', '1')
        self.assertEqual(tcl.eval('set a(1)'), '1')

    def testGetVar(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.getvar('a'), '1')

    def testGetVarArray(self):
        tcl = self.interp
        tcl.eval('set a(1) 1')
        self.assertEqual(tcl.getvar('a(1)'), '1')

    def testGetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.getvar, 'a')

    def testGetVarArrayException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.getvar, 'a(1)')

    def testUnsetVar(self):
        tcl = self.interp
        tcl.setvar('a', 1)
        self.assertEqual(tcl.eval('info exists a'), '1')
        tcl.unsetvar('a')
        self.assertEqual(tcl.eval('info exists a'), '0')

    def testUnsetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)', 1)
        tcl.setvar('a(2)', 2)
        self.assertEqual(tcl.eval('info exists a(1)'), '1')
        self.assertEqual(tcl.eval('info exists a(2)'), '1')
        tcl.unsetvar('a(1)')
        self.assertEqual(tcl.eval('info exists a(1)'), '0')
        self.assertEqual(tcl.eval('info exists a(2)'), '1')

    def testUnsetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.unsetvar, 'a')

    def get_integers(self):
        integers = (0, 1, -1, 2**31 - 1, -2**31, 2**31, -2**31 - 1, 2**63 - 1,
                    -2**63)
        # bignum was added in Tcl 8.5, but its support is able only since 8.5.8.
        # Actually it is determined at compile time, so using get_tk_patchlevel()
        # is not reliable.
        # TODO: expose full static version.
        if tcl_version >= (8, 5):
            v = get_tk_patchlevel()
            if v >= (8, 6, 0, 'final') or (8, 5, 8) <= v < (8, 6):
                integers += (2**63, -2**63 - 1, 2**1000, -2**1000)
        return integers

    def test_getint(self):
        tcl = self.interp.tk
        for i in self.get_integers():
            self.assertEqual(tcl.getint(' %d ' % i), i)
            if tcl_version >= (8, 5):
                self.assertEqual(tcl.getint(' %#o ' % i), i)
            self.assertEqual(tcl.getint((' %#o ' % i).replace('o', '')), i)
            self.assertEqual(tcl.getint(' %#x ' % i), i)
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            self.assertRaises(TclError, tcl.getint, str(2**1000))
        self.assertEqual(tcl.getint(42), 42)
        self.assertRaises(TypeError, tcl.getint)
        self.assertRaises(TypeError, tcl.getint, '42', '10')
        self.assertRaises(TypeError, tcl.getint, b'42')
        self.assertRaises(TypeError, tcl.getint, 42.0)
        self.assertRaises(TclError, tcl.getint, 'a')
        self.assertRaises((TypeError, ValueError, TclError), tcl.getint,
                          '42\0')
        self.assertRaises((UnicodeEncodeError, ValueError, TclError),
                          tcl.getint, '42\ud800')

    def test_getdouble(self):
        tcl = self.interp.tk
        self.assertEqual(tcl.getdouble(' 42 '), 42.0)
        self.assertEqual(tcl.getdouble(' 42.5 '), 42.5)
        self.assertEqual(tcl.getdouble(42.5), 42.5)
        self.assertEqual(tcl.getdouble(42), 42.0)
        self.assertRaises(TypeError, tcl.getdouble)
        self.assertRaises(TypeError, tcl.getdouble, '42.5', '10')
        self.assertRaises(TypeError, tcl.getdouble, b'42.5')
        self.assertRaises(TclError, tcl.getdouble, 'a')
        self.assertRaises((TypeError, ValueError, TclError), tcl.getdouble,
                          '42.5\0')
        self.assertRaises((UnicodeEncodeError, ValueError, TclError),
                          tcl.getdouble, '42.5\ud800')

    def test_getboolean(self):
        tcl = self.interp.tk
        self.assertIs(tcl.getboolean('on'), True)
        self.assertIs(tcl.getboolean('1'), True)
        self.assertIs(tcl.getboolean(42), True)
        self.assertIs(tcl.getboolean(0), False)
        self.assertRaises(TypeError, tcl.getboolean)
        self.assertRaises(TypeError, tcl.getboolean, 'on', '1')
        self.assertRaises(TypeError, tcl.getboolean, b'on')
        self.assertRaises(TypeError, tcl.getboolean, 1.0)
        self.assertRaises(TclError, tcl.getboolean, 'a')
        self.assertRaises((TypeError, ValueError, TclError), tcl.getboolean,
                          'on\0')
        self.assertRaises((UnicodeEncodeError, ValueError, TclError),
                          tcl.getboolean, 'on\ud800')

    def testEvalFile(self):
        tcl = self.interp
        filename = os_helper.TESTFN_ASCII
        self.addCleanup(os_helper.unlink, filename)
        with open(filename, 'w') as f:
            f.write("""set a 1
            set b 2
            set c [ expr $a + $b ]
            """)
        tcl.evalfile(filename)
        self.assertEqual(tcl.eval('set a'), '1')
        self.assertEqual(tcl.eval('set b'), '2')
        self.assertEqual(tcl.eval('set c'), '3')

    def test_evalfile_null_in_result(self):
        tcl = self.interp
        filename = os_helper.TESTFN_ASCII
        self.addCleanup(os_helper.unlink, filename)
        with open(filename, 'w') as f:
            f.write("""
            set a "a\0b"
            set b "a\\0b"
            """)
        tcl.evalfile(filename)
        self.assertEqual(tcl.eval('set a'), 'a\x00b')
        self.assertEqual(tcl.eval('set b'), 'a\x00b')

    def test_evalfile_surrogates_in_result(self):
        tcl = self.interp
        encoding = tcl.call('encoding', 'system')
        self.addCleanup(tcl.call, 'encoding', 'system', encoding)
        tcl.call('encoding', 'system', 'utf-8')

        filename = os_helper.TESTFN_ASCII
        self.addCleanup(os_helper.unlink, filename)
        with open(filename, 'wb') as f:
            f.write(b"""
            set a "<\xed\xa0\xbd\xed\xb2\xbb>"
            set b "<\\ud83d\\udcbb>"
            """)
        tcl.evalfile(filename)
        self.assertEqual(tcl.eval('set a'), '<\U0001f4bb>')
        self.assertEqual(tcl.eval('set b'), '<\U0001f4bb>')

    def testEvalFileException(self):
        tcl = self.interp
        filename = "doesnotexists"
        try:
            os.remove(filename)
        except Exception as e:
            pass
        self.assertRaises(TclError, tcl.evalfile, filename)

    def testPackageRequireException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.eval, 'package require DNE')

    @unittest.skipUnless(sys.platform == 'win32', 'Requires Windows')
    def testLoadWithUNC(self):
        # Build a UNC path from the regular path.
        # Something like
        #   \\%COMPUTERNAME%\c$\python27\python.exe

        fullname = os.path.abspath(sys.executable)
        if fullname[1] != ':':
            raise unittest.SkipTest('Absolute path should have drive part')
        unc_name = r'\\%s\%s$\%s' % (os.environ['COMPUTERNAME'], fullname[0],
                                     fullname[3:])
        if not os.path.exists(unc_name):
            raise unittest.SkipTest('Cannot connect to UNC Path')

        with os_helper.EnvironmentVarGuard() as env:
            env.unset("TCL_LIBRARY")
            stdout = subprocess.check_output(
                [unc_name, '-c', 'import tkinter; print(tkinter)'])

        self.assertIn(b'tkinter', stdout)

    def test_exprstring(self):
        tcl = self.interp
        tcl.call('set', 'a', 3)
        tcl.call('set', 'b', 6)

        def check(expr, expected):
            result = tcl.exprstring(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, str)

        self.assertRaises(TypeError, tcl.exprstring)
        self.assertRaises(TypeError, tcl.exprstring, '8.2', '+6')
        self.assertRaises(TypeError, tcl.exprstring, b'8.2 + 6')
        self.assertRaises(TclError, tcl.exprstring, 'spam')
        check('', '0')
        check('8.2 + 6', '14.2')
        check('3.1 + $a', '6.1')
        check('2 + "$a.$b"', '5.6')
        check('4*[llength "6 2"]', '8')
        check('{word one} < "word $a"', '0')
        check('4*2 < 7', '0')
        check('hypot($a, 4)', '5.0')
        check('5 / 4', '1')
        check('5 / 4.0', '1.25')
        check('5 / ( [string length "abcd"] + 0.0 )', '1.25')
        check('20.0/5.0', '4.0')
        check('"0x03" > "2"', '1')
        check('[string length "a\xbd\u20ac"]', '3')
        check(r'[string length "a\xbd\u20ac"]', '3')
        check('"abc"', 'abc')
        check('"a\xbd\u20ac"', 'a\xbd\u20ac')
        check(r'"a\xbd\u20ac"', 'a\xbd\u20ac')
        check(r'"a\0b"', 'a\x00b')
        if tcl_version >= (8, 5):  # bignum was added in Tcl 8.5
            check('2**64', str(2**64))

    def test_exprdouble(self):
        tcl = self.interp
        tcl.call('set', 'a', 3)
        tcl.call('set', 'b', 6)

        def check(expr, expected):
            result = tcl.exprdouble(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, float)

        self.assertRaises(TypeError, tcl.exprdouble)
        self.assertRaises(TypeError, tcl.exprdouble, '8.2', '+6')
        self.assertRaises(TypeError, tcl.exprdouble, b'8.2 + 6')
        self.assertRaises(TclError, tcl.exprdouble, 'spam')
        check('', 0.0)
        check('8.2 + 6', 14.2)
        check('3.1 + $a', 6.1)
        check('2 + "$a.$b"', 5.6)
        check('4*[llength "6 2"]', 8.0)
        check('{word one} < "word $a"', 0.0)
        check('4*2 < 7', 0.0)
        check('hypot($a, 4)', 5.0)
        check('5 / 4', 1.0)
        check('5 / 4.0', 1.25)
        check('5 / ( [string length "abcd"] + 0.0 )', 1.25)
        check('20.0/5.0', 4.0)
        check('"0x03" > "2"', 1.0)
        check('[string length "a\xbd\u20ac"]', 3.0)
        check(r'[string length "a\xbd\u20ac"]', 3.0)
        self.assertRaises(TclError, tcl.exprdouble, '"abc"')
        if tcl_version >= (8, 5):  # bignum was added in Tcl 8.5
            check('2**64', float(2**64))

    def test_exprlong(self):
        tcl = self.interp
        tcl.call('set', 'a', 3)
        tcl.call('set', 'b', 6)

        def check(expr, expected):
            result = tcl.exprlong(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, int)

        self.assertRaises(TypeError, tcl.exprlong)
        self.assertRaises(TypeError, tcl.exprlong, '8.2', '+6')
        self.assertRaises(TypeError, tcl.exprlong, b'8.2 + 6')
        self.assertRaises(TclError, tcl.exprlong, 'spam')
        check('', 0)
        check('8.2 + 6', 14)
        check('3.1 + $a', 6)
        check('2 + "$a.$b"', 5)
        check('4*[llength "6 2"]', 8)
        check('{word one} < "word $a"', 0)
        check('4*2 < 7', 0)
        check('hypot($a, 4)', 5)
        check('5 / 4', 1)
        check('5 / 4.0', 1)
        check('5 / ( [string length "abcd"] + 0.0 )', 1)
        check('20.0/5.0', 4)
        check('"0x03" > "2"', 1)
        check('[string length "a\xbd\u20ac"]', 3)
        check(r'[string length "a\xbd\u20ac"]', 3)
        self.assertRaises(TclError, tcl.exprlong, '"abc"')
        if tcl_version >= (8, 5):  # bignum was added in Tcl 8.5
            self.assertRaises(TclError, tcl.exprlong, '2**64')

    def test_exprboolean(self):
        tcl = self.interp
        tcl.call('set', 'a', 3)
        tcl.call('set', 'b', 6)

        def check(expr, expected):
            result = tcl.exprboolean(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, int)
            self.assertNotIsInstance(result, bool)

        self.assertRaises(TypeError, tcl.exprboolean)
        self.assertRaises(TypeError, tcl.exprboolean, '8.2', '+6')
        self.assertRaises(TypeError, tcl.exprboolean, b'8.2 + 6')
        self.assertRaises(TclError, tcl.exprboolean, 'spam')
        check('', False)
        for value in ('0', 'false', 'no', 'off'):
            check(value, False)
            check('"%s"' % value, False)
            check('{%s}' % value, False)
        for value in ('1', 'true', 'yes', 'on'):
            check(value, True)
            check('"%s"' % value, True)
            check('{%s}' % value, True)
        check('8.2 + 6', True)
        check('3.1 + $a', True)
        check('2 + "$a.$b"', True)
        check('4*[llength "6 2"]', True)
        check('{word one} < "word $a"', False)
        check('4*2 < 7', False)
        check('hypot($a, 4)', True)
        check('5 / 4', True)
        check('5 / 4.0', True)
        check('5 / ( [string length "abcd"] + 0.0 )', True)
        check('20.0/5.0', True)
        check('"0x03" > "2"', True)
        check('[string length "a\xbd\u20ac"]', True)
        check(r'[string length "a\xbd\u20ac"]', True)
        self.assertRaises(TclError, tcl.exprboolean, '"abc"')
        if tcl_version >= (8, 5):  # bignum was added in Tcl 8.5
            check('2**64', True)

    @unittest.skipUnless(tcl_version >= (8, 5), 'requires Tcl version >= 8.5')
    def test_booleans(self):
        tcl = self.interp

        def check(expr, expected):
            result = tcl.call('expr', expr)
            if tcl.wantobjects():
                self.assertEqual(result, expected)
                self.assertIsInstance(result, int)
            else:
                self.assertIn(result, (expr, str(int(expected))))
                self.assertIsInstance(result, str)

        check('true', True)
        check('yes', True)
        check('on', True)
        check('false', False)
        check('no', False)
        check('off', False)
        check('1 < 2', True)
        check('1 > 2', False)

    def test_expr_bignum(self):
        tcl = self.interp
        for i in self.get_integers():
            result = tcl.call('expr', str(i))
            if self.wantobjects:
                self.assertEqual(result, i)
                self.assertIsInstance(result, int)
            else:
                self.assertEqual(result, str(i))
                self.assertIsInstance(result, str)
        if get_tk_patchlevel() < (8, 5):  # bignum was added in Tcl 8.5
            self.assertRaises(TclError, tcl.call, 'expr', str(2**1000))

    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)

        self.assertEqual(passValue(True), True if self.wantobjects else '1')
        self.assertEqual(passValue(False), False if self.wantobjects else '0')
        self.assertEqual(passValue('string'), 'string')
        self.assertEqual(passValue('string\u20ac'), 'string\u20ac')
        self.assertEqual(passValue('string\U0001f4bb'), 'string\U0001f4bb')
        self.assertEqual(passValue('str\x00ing'), 'str\x00ing')
        self.assertEqual(passValue('str\x00ing\xbd'), 'str\x00ing\xbd')
        self.assertEqual(passValue('str\x00ing\u20ac'), 'str\x00ing\u20ac')
        self.assertEqual(passValue('str\x00ing\U0001f4bb'),
                         'str\x00ing\U0001f4bb')
        if sys.platform != 'win32':
            self.assertEqual(passValue('<\udce2\udc82\udcac>'), '<\u20ac>')
            self.assertEqual(
                passValue('<\udced\udca0\udcbd\udced\udcb2\udcbb>'),
                '<\U0001f4bb>')
        self.assertEqual(passValue(b'str\x00ing'),
                         b'str\x00ing' if self.wantobjects else 'str\x00ing')
        self.assertEqual(
            passValue(b'str\xc0\x80ing'),
            b'str\xc0\x80ing' if self.wantobjects else 'str\xc0\x80ing')
        self.assertEqual(passValue(b'str\xbding'),
                         b'str\xbding' if self.wantobjects else 'str\xbding')
        for i in self.get_integers():
            self.assertEqual(passValue(i), i if self.wantobjects else str(i))
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            self.assertEqual(passValue(2**1000), str(2**1000))
        for f in (0.0, 1.0, -1.0, 1 / 3, sys.float_info.min,
                  sys.float_info.max, -sys.float_info.min,
                  -sys.float_info.max):
            if self.wantobjects:
                self.assertEqual(passValue(f), f)
            else:
                self.assertEqual(float(passValue(f)), f)
        if self.wantobjects:
            f = passValue(float('nan'))
            self.assertNotEqual(f, f)
            self.assertEqual(passValue(float('inf')), float('inf'))
            self.assertEqual(passValue(-float('inf')), -float('inf'))
        else:
            self.assertEqual(float(passValue(float('inf'))), float('inf'))
            self.assertEqual(float(passValue(-float('inf'))), -float('inf'))
            # XXX NaN representation can be not parsable by float()
        self.assertEqual(passValue((1, '2', (3.4, ))),
                         (1, '2', (3.4, )) if self.wantobjects else '1 2 3.4')
        self.assertEqual(passValue(['a', ['b', 'c']]),
                         ('a', ('b', 'c')) if self.wantobjects else 'a {b c}')

    def test_user_command(self):
        result = None

        def testfunc(arg):
            nonlocal result
            result = arg
            return arg

        self.interp.createcommand('testfunc', testfunc)
        self.addCleanup(self.interp.tk.deletecommand, 'testfunc')

        def check(value, expected=None, *, eq=self.assertEqual):
            if expected is None:
                expected = value
            nonlocal result
            result = None
            r = self.interp.call('testfunc', value)
            self.assertIsInstance(result, str)
            eq(result, expected)
            self.assertIsInstance(r, str)
            eq(r, expected)

        def float_eq(actual, expected):
            self.assertAlmostEqual(float(actual),
                                   expected,
                                   delta=abs(expected) * 1e-10)

        check(True, '1')
        check(False, '0')
        check('string')
        check('string\xbd')
        check('string\u20ac')
        check('string\U0001f4bb')
        if sys.platform != 'win32':
            check('<\udce2\udc82\udcac>', '<\u20ac>')
            check('<\udced\udca0\udcbd\udced\udcb2\udcbb>', '<\U0001f4bb>')
        check('')
        check(b'string', 'string')
        check(b'string\xe2\x82\xac', 'string\xe2\x82\xac')
        check(b'string\xbd', 'string\xbd')
        check(b'', '')
        check('str\x00ing')
        check('str\x00ing\xbd')
        check('str\x00ing\u20ac')
        check(b'str\x00ing', 'str\x00ing')
        check(b'str\xc0\x80ing', 'str\xc0\x80ing')
        check(b'str\xc0\x80ing\xe2\x82\xac', 'str\xc0\x80ing\xe2\x82\xac')
        for i in self.get_integers():
            check(i, str(i))
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            check(2**1000, str(2**1000))
        for f in (0.0, 1.0, -1.0):
            check(f, repr(f))
        for f in (1 / 3.0, sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            check(f, eq=float_eq)
        check(float('inf'), eq=float_eq)
        check(-float('inf'), eq=float_eq)
        # XXX NaN representation can be not parsable by float()
        check((), '')
        check((1, (2, ), (3, 4), '5 6', ()), '1 2 {3 4} {5 6} {}')
        check([1, [
            2,
        ], [3, 4], '5 6', []], '1 2 {3 4} {5 6} {}')

    def test_splitlist(self):
        splitlist = self.interp.tk.splitlist
        call = self.interp.tk.call
        self.assertRaises(TypeError, splitlist)
        self.assertRaises(TypeError, splitlist, 'a', 'b')
        self.assertRaises(TypeError, splitlist, 2)
        testcases = [
            ('2', ('2', )),
            ('', ()),
            ('{}', ('', )),
            ('""', ('', )),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (b'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \u20ac', ('a', '\u20ac')),
            ('a \U0001f4bb', ('a', '\U0001f4bb')),
            (b'a \xe2\x82\xac', ('a', '\u20ac')),
            (b'a \xf0\x9f\x92\xbb', ('a', '\U0001f4bb')),
            (b'a \xed\xa0\xbd\xed\xb2\xbb', ('a', '\U0001f4bb')),
            (b'a\xc0\x80b c\xc0\x80d', ('a\x00b', 'c\x00d')),
            ('a {b c}', ('a', 'b c')),
            (r'a b\ c', ('a', 'b c')),
            (('a', 'b c'), ('a', 'b c')),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            ((), ()),
            ([], ()),
            (['a', ['b', 'c']], ('a', ['b', 'c'])),
            (call('list', 1, '2',
                  (3.4, )), (1, '2', (3.4, )) if self.wantobjects else
             ('1', '2', '3.4')),
        ]
        tk_patchlevel = get_tk_patchlevel()
        if tcl_version >= (8, 5):
            if not self.wantobjects or tk_patchlevel < (8, 5, 5):
                # Before 8.5.5 dicts were converted to lists through string
                expected = ('12', '\u20ac', '\xe2\x82\xac', '3.4')
            else:
                expected = (12, '\u20ac', b'\xe2\x82\xac', (3.4, ))
            testcases += [
                (call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac',
                      (3.4, )), expected),
            ]
        dbg_info = ('want objects? %s, Tcl version: %s, Tk patchlevel: %s' %
                    (self.wantobjects, tcl_version, tk_patchlevel))
        for arg, res in testcases:
            self.assertEqual(splitlist(arg), res,
                             'arg=%a, %s' % (arg, dbg_info))
        self.assertRaises(TclError, splitlist, '{')

    def test_split(self):
        split = self.interp.tk.split
        call = self.interp.tk.call
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', r'\bsplit\b.*\bsplitlist\b',
                                    DeprecationWarning)
            self.assertRaises(TypeError, split)
            self.assertRaises(TypeError, split, 'a', 'b')
            self.assertRaises(TypeError, split, 2)
        testcases = [
            ('2', '2'),
            ('', ''),
            ('{}', ''),
            ('""', ''),
            ('{', '{'),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (b'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \u20ac', ('a', '\u20ac')),
            (b'a \xe2\x82\xac', ('a', '\u20ac')),
            (b'a\xc0\x80b', 'a\x00b'),
            (b'a\xc0\x80b c\xc0\x80d', ('a\x00b', 'c\x00d')),
            (b'{a\xc0\x80b c\xc0\x80d', '{a\x00b c\x00d'),
            ('a {b c}', ('a', ('b', 'c'))),
            (r'a b\ c', ('a', ('b', 'c'))),
            (('a', b'b c'), ('a', ('b', 'c'))),
            (('a', 'b c'), ('a', ('b', 'c'))),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            (('a', (2, 3.4)), ('a', (2, 3.4))),
            ((), ()),
            ([], ()),
            (['a', 'b c'], ('a', ('b', 'c'))),
            (['a', ['b', 'c']], ('a', ('b', 'c'))),
            (call('list', 1, '2',
                  (3.4, )), (1, '2', (3.4, )) if self.wantobjects else
             ('1', '2', '3.4')),
        ]
        if tcl_version >= (8, 5):
            if not self.wantobjects or get_tk_patchlevel() < (8, 5, 5):
                # Before 8.5.5 dicts were converted to lists through string
                expected = ('12', '\u20ac', '\xe2\x82\xac', '3.4')
            else:
                expected = (12, '\u20ac', b'\xe2\x82\xac', (3.4, ))
            testcases += [
                (call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac',
                      (3.4, )), expected),
            ]
        for arg, res in testcases:
            with self.assertWarns(DeprecationWarning):
                self.assertEqual(split(arg), res, msg=arg)

    def test_splitdict(self):
        splitdict = tkinter._splitdict
        tcl = self.interp.tk

        arg = '-a {1 2 3} -something foo status {}'
        self.assertEqual(splitdict(tcl, arg, False), {
            '-a': '1 2 3',
            '-something': 'foo',
            'status': ''
        })
        self.assertEqual(splitdict(tcl, arg), {
            'a': '1 2 3',
            'something': 'foo',
            'status': ''
        })

        arg = ('-a', (1, 2, 3), '-something', 'foo', 'status', '{}')
        self.assertEqual(splitdict(tcl, arg, False), {
            '-a': (1, 2, 3),
            '-something': 'foo',
            'status': '{}'
        })
        self.assertEqual(splitdict(tcl, arg), {
            'a': (1, 2, 3),
            'something': 'foo',
            'status': '{}'
        })

        self.assertRaises(RuntimeError, splitdict, tcl, '-a b -c ')
        self.assertRaises(RuntimeError, splitdict, tcl, ('-a', 'b', '-c'))

        arg = tcl.call('list', '-a', (1, 2, 3), '-something', 'foo', 'status',
                       ())
        self.assertEqual(
            splitdict(tcl, arg), {
                'a': (1, 2, 3) if self.wantobjects else '1 2 3',
                'something': 'foo',
                'status': ''
            })

        if tcl_version >= (8, 5):
            arg = tcl.call('dict', 'create', '-a', (1, 2, 3), '-something',
                           'foo', 'status', ())
            if not self.wantobjects or get_tk_patchlevel() < (8, 5, 5):
                # Before 8.5.5 dicts were converted to lists through string
                expected = {'a': '1 2 3', 'something': 'foo', 'status': ''}
            else:
                expected = {'a': (1, 2, 3), 'something': 'foo', 'status': ''}
            self.assertEqual(splitdict(tcl, arg), expected)

    def test_join(self):
        join = tkinter._join
        tcl = self.interp.tk

        def unpack(s):
            return tcl.call('lindex', s, 0)

        def check(value):
            self.assertEqual(unpack(join([value])), value)
            self.assertEqual(unpack(join([value, 0])), value)
            self.assertEqual(unpack(unpack(join([[value]]))), value)
            self.assertEqual(unpack(unpack(join([[value, 0]]))), value)
            self.assertEqual(unpack(unpack(join([[value], 0]))), value)
            self.assertEqual(unpack(unpack(join([[value, 0], 0]))), value)

        check('')
        check('spam')
        check('sp am')
        check('sp\tam')
        check('sp\nam')
        check(' \t\n')
        check('{spam}')
        check('{sp am}')
        check('"spam"')
        check('"sp am"')
        check('{"spam"}')
        check('"{spam}"')
        check('sp\\am')
        check('"sp\\am"')
        check('"{}" "{}"')
        check('"\\')
        check('"{')
        check('"}')
        check('\n\\')
        check('\n{')
        check('\n}')
        check('\\\n')
        check('{\n')
        check('}\n')

    @support.cpython_only
    def test_new_tcl_obj(self):
        support.check_disallow_instantiation(self, _tkinter.Tcl_Obj)
        support.check_disallow_instantiation(self, _tkinter.TkttType)
        support.check_disallow_instantiation(self, _tkinter.TkappType)
Exemplo n.º 25
0
class TclTest(unittest.TestCase):

    def setUp(self):
        self.interp = Tcl()

    def testEval(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.eval('set a'),'1')

    def testEvalException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'set a')

    def testEvalException2(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'this is wrong')

    def testCall(self):
        tcl = self.interp
        tcl.call('set','a','1')
        self.assertEqual(tcl.call('set','a'),'1')

    def testCallException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.call,'set','a')

    def testCallException2(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.call,'this','is','wrong')

    def testSetVar(self):
        tcl = self.interp
        tcl.setvar('a','1')
        self.assertEqual(tcl.eval('set a'),'1')

    def testSetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)','1')
        self.assertEqual(tcl.eval('set a(1)'),'1')

    def testGetVar(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.getvar('a'),'1')

    def testGetVarArray(self):
        tcl = self.interp
        tcl.eval('set a(1) 1')
        self.assertEqual(tcl.getvar('a(1)'),'1')

    def testGetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.getvar,'a')

    def testGetVarArrayException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.getvar,'a(1)')

    def testUnsetVar(self):
        tcl = self.interp
        tcl.setvar('a',1)
        self.assertEqual(tcl.eval('info exists a'),'1')
        tcl.unsetvar('a')
        self.assertEqual(tcl.eval('info exists a'),'0')

    def testUnsetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)',1)
        tcl.setvar('a(2)',2)
        self.assertEqual(tcl.eval('info exists a(1)'),'1')
        self.assertEqual(tcl.eval('info exists a(2)'),'1')
        tcl.unsetvar('a(1)')
        self.assertEqual(tcl.eval('info exists a(1)'),'0')
        self.assertEqual(tcl.eval('info exists a(2)'),'1')

    def testUnsetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.unsetvar,'a')

    def testEvalFile(self):
        tcl = self.interp
        filename = "testEvalFile.tcl"
        fd = open(filename,'w')
        script = """set a 1
        set b 2
        set c [ expr $a + $b ]
        """
        fd.write(script)
        fd.close()
        tcl.evalfile(filename)
        os.remove(filename)
        self.assertEqual(tcl.eval('set a'),'1')
        self.assertEqual(tcl.eval('set b'),'2')
        self.assertEqual(tcl.eval('set c'),'3')

    def testEvalFileException(self):
        tcl = self.interp
        filename = "doesnotexists"
        try:
            os.remove(filename)
        except Exception as e:
            pass
        self.assertRaises(TclError,tcl.evalfile,filename)

    def testPackageRequireException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'package require DNE')

    @unittest.skipUnless(sys.platform == 'win32', 'Requires Windows')
    def testLoadWithUNC(self):
        # Build a UNC path from the regular path.
        # Something like
        #   \\%COMPUTERNAME%\c$\python27\python.exe

        fullname = os.path.abspath(sys.executable)
        if fullname[1] != ':':
            raise unittest.SkipTest('Absolute path should have drive part')
        unc_name = r'\\%s\%s$\%s' % (os.environ['COMPUTERNAME'],
                                    fullname[0],
                                    fullname[3:])
        if not os.path.exists(unc_name):
            raise unittest.SkipTest('Cannot connect to UNC Path')

        with support.EnvironmentVarGuard() as env:
            env.unset("TCL_LIBRARY")
            f = os.popen('%s -c "import tkinter; print(tkinter)"' % (unc_name,))

        self.assertIn('tkinter', f.read())
        # exit code must be zero
        self.assertEqual(f.close(), None)

    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)

        self.assertEqual(passValue(True), True)
        self.assertEqual(passValue(False), False)
        self.assertEqual(passValue('string'), 'string')
        self.assertEqual(passValue('string\u20ac'), 'string\u20ac')
        for i in (0, 1, -1, 2**31-1, -2**31):
            self.assertEqual(passValue(i), i)
        for f in (0.0, 1.0, -1.0, 1/3,
                  sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            self.assertEqual(passValue(f), f)
        for f in float('nan'), float('inf'), -float('inf'):
            if f != f: # NaN
                self.assertNotEqual(passValue(f), f)
            else:
                self.assertEqual(passValue(f), f)
        self.assertEqual(passValue((1, '2', (3.4,))), (1, '2', (3.4,)))

    def test_splitlist(self):
        splitlist = self.interp.tk.splitlist
        call = self.interp.tk.call
        self.assertRaises(TypeError, splitlist)
        self.assertRaises(TypeError, splitlist, 'a', 'b')
        self.assertRaises(TypeError, splitlist, 2)
        testcases = [
            ('2', ('2',)),
            ('', ()),
            ('{}', ('',)),
            ('""', ('',)),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (b'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \u20ac', ('a', '\u20ac')),
            (b'a \xe2\x82\xac', ('a', '\u20ac')),
            ('a {b c}', ('a', 'b c')),
            (r'a b\ c', ('a', 'b c')),
            (('a', 'b c'), ('a', 'b c')),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            ((), ()),
            (call('list', 1, '2', (3.4,)), (1, '2', (3.4,))),
        ]
        for arg, res in testcases:
            self.assertEqual(splitlist(arg), res, msg=arg)
        self.assertRaises(TclError, splitlist, '{')

    def test_split(self):
        split = self.interp.tk.split
        call = self.interp.tk.call
        self.assertRaises(TypeError, split)
        self.assertRaises(TypeError, split, 'a', 'b')
        self.assertRaises(TypeError, split, 2)
        testcases = [
            ('2', '2'),
            ('', ''),
            ('{}', ''),
            ('""', ''),
            ('{', '{'),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (b'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \u20ac', ('a', '\u20ac')),
            (b'a \xe2\x82\xac', ('a', '\u20ac')),
            ('a {b c}', ('a', ('b', 'c'))),
            (r'a b\ c', ('a', ('b', 'c'))),
            (('a', b'b c'), ('a', ('b', 'c'))),
            (('a', 'b c'), ('a', ('b', 'c'))),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            (('a', (2, 3.4)), ('a', (2, 3.4))),
            ((), ()),
            (call('list', 1, '2', (3.4,)), (1, '2', (3.4,))),
        ]
        for arg, res in testcases:
            self.assertEqual(split(arg), res, msg=arg)
Exemplo n.º 26
0
class TclTest(unittest.TestCase):
    def setUp(self):
        self.interp = Tcl()
        self.wantobjects = self.interp.tk.wantobjects()

    def testEval(self):
        tcl = self.interp
        tcl.eval("set a 1")
        self.assertEqual(tcl.eval("set a"), "1")

    def test_eval_null_in_result(self):
        tcl = self.interp
        self.assertEqual(tcl.eval('set a "a\\0b"'), "a\x00b")

    def testEvalException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.eval, "set a")

    def testEvalException2(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.eval, "this is wrong")

    def testCall(self):
        tcl = self.interp
        tcl.call("set", "a", "1")
        self.assertEqual(tcl.call("set", "a"), "1")

    def testCallException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.call, "set", "a")

    def testCallException2(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.call, "this", "is", "wrong")

    def testSetVar(self):
        tcl = self.interp
        tcl.setvar("a", "1")
        self.assertEqual(tcl.eval("set a"), "1")

    def testSetVarArray(self):
        tcl = self.interp
        tcl.setvar("a(1)", "1")
        self.assertEqual(tcl.eval("set a(1)"), "1")

    def testGetVar(self):
        tcl = self.interp
        tcl.eval("set a 1")
        self.assertEqual(tcl.getvar("a"), "1")

    def testGetVarArray(self):
        tcl = self.interp
        tcl.eval("set a(1) 1")
        self.assertEqual(tcl.getvar("a(1)"), "1")

    def testGetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.getvar, "a")

    def testGetVarArrayException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.getvar, "a(1)")

    def testUnsetVar(self):
        tcl = self.interp
        tcl.setvar("a", 1)
        self.assertEqual(tcl.eval("info exists a"), "1")
        tcl.unsetvar("a")
        self.assertEqual(tcl.eval("info exists a"), "0")

    def testUnsetVarArray(self):
        tcl = self.interp
        tcl.setvar("a(1)", 1)
        tcl.setvar("a(2)", 2)
        self.assertEqual(tcl.eval("info exists a(1)"), "1")
        self.assertEqual(tcl.eval("info exists a(2)"), "1")
        tcl.unsetvar("a(1)")
        self.assertEqual(tcl.eval("info exists a(1)"), "0")
        self.assertEqual(tcl.eval("info exists a(2)"), "1")

    def testUnsetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.unsetvar, "a")

    def testEvalFile(self):
        tcl = self.interp
        with open(support.TESTFN, "w") as f:
            self.addCleanup(support.unlink, support.TESTFN)
            f.write(
                """set a 1
            set b 2
            set c [ expr $a + $b ]
            """
            )
        tcl.evalfile(support.TESTFN)
        self.assertEqual(tcl.eval("set a"), "1")
        self.assertEqual(tcl.eval("set b"), "2")
        self.assertEqual(tcl.eval("set c"), "3")

    def test_evalfile_null_in_result(self):
        tcl = self.interp
        with open(support.TESTFN, "w") as f:
            self.addCleanup(support.unlink, support.TESTFN)
            f.write(
                """
            set a "a\0b"
            set b "a\\0b"
            """
            )
        tcl.evalfile(support.TESTFN)
        self.assertEqual(tcl.eval("set a"), "a\x00b")
        self.assertEqual(tcl.eval("set b"), "a\x00b")

    def testEvalFileException(self):
        tcl = self.interp
        filename = "doesnotexists"
        try:
            os.remove(filename)
        except Exception as e:
            pass
        self.assertRaises(TclError, tcl.evalfile, filename)

    def testPackageRequireException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.eval, "package require DNE")

    @unittest.skipUnless(sys.platform == "win32", "Requires Windows")
    def testLoadWithUNC(self):
        # Build a UNC path from the regular path.
        # Something like
        #   \\%COMPUTERNAME%\c$\python27\python.exe

        fullname = os.path.abspath(sys.executable)
        if fullname[1] != ":":
            raise unittest.SkipTest("Absolute path should have drive part")
        unc_name = r"\\%s\%s$\%s" % (os.environ["COMPUTERNAME"], fullname[0], fullname[3:])
        if not os.path.exists(unc_name):
            raise unittest.SkipTest("Cannot connect to UNC Path")

        with support.EnvironmentVarGuard() as env:
            env.unset("TCL_LIBRARY")
            f = os.popen('%s -c "import tkinter; print(tkinter)"' % (unc_name,))

        self.assertIn("tkinter", f.read())
        # exit code must be zero
        self.assertEqual(f.close(), None)

    def test_exprstring(self):
        tcl = self.interp
        tcl.call("set", "a", 3)
        tcl.call("set", "b", 6)

        def check(expr, expected):
            result = tcl.exprstring(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, str)

        self.assertRaises(TypeError, tcl.exprstring)
        self.assertRaises(TypeError, tcl.exprstring, "8.2", "+6")
        self.assertRaises(TypeError, tcl.exprstring, b"8.2 + 6")
        self.assertRaises(TclError, tcl.exprstring, "spam")
        check("", "0")
        check("8.2 + 6", "14.2")
        check("3.1 + $a", "6.1")
        check('2 + "$a.$b"', "5.6")
        check('4*[llength "6 2"]', "8")
        check('{word one} < "word $a"', "0")
        check("4*2 < 7", "0")
        check("hypot($a, 4)", "5.0")
        check("5 / 4", "1")
        check("5 / 4.0", "1.25")
        check('5 / ( [string length "abcd"] + 0.0 )', "1.25")
        check("20.0/5.0", "4.0")
        check('"0x03" > "2"', "1")
        check('[string length "a\xbd\u20ac"]', "3")
        check(r'[string length "a\xbd\u20ac"]', "3")
        check('"abc"', "abc")
        check('"a\xbd\u20ac"', "a\xbd\u20ac")
        check(r'"a\xbd\u20ac"', "a\xbd\u20ac")
        check(r'"a\0b"', "a\x00b")
        if tcl_version >= (8, 5):
            check("2**64", str(2 ** 64))

    def test_exprdouble(self):
        tcl = self.interp
        tcl.call("set", "a", 3)
        tcl.call("set", "b", 6)

        def check(expr, expected):
            result = tcl.exprdouble(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, float)

        self.assertRaises(TypeError, tcl.exprdouble)
        self.assertRaises(TypeError, tcl.exprdouble, "8.2", "+6")
        self.assertRaises(TypeError, tcl.exprdouble, b"8.2 + 6")
        self.assertRaises(TclError, tcl.exprdouble, "spam")
        check("", 0.0)
        check("8.2 + 6", 14.2)
        check("3.1 + $a", 6.1)
        check('2 + "$a.$b"', 5.6)
        check('4*[llength "6 2"]', 8.0)
        check('{word one} < "word $a"', 0.0)
        check("4*2 < 7", 0.0)
        check("hypot($a, 4)", 5.0)
        check("5 / 4", 1.0)
        check("5 / 4.0", 1.25)
        check('5 / ( [string length "abcd"] + 0.0 )', 1.25)
        check("20.0/5.0", 4.0)
        check('"0x03" > "2"', 1.0)
        check('[string length "a\xbd\u20ac"]', 3.0)
        check(r'[string length "a\xbd\u20ac"]', 3.0)
        self.assertRaises(TclError, tcl.exprdouble, '"abc"')
        if tcl_version >= (8, 5):
            check("2**64", float(2 ** 64))

    def test_exprlong(self):
        tcl = self.interp
        tcl.call("set", "a", 3)
        tcl.call("set", "b", 6)

        def check(expr, expected):
            result = tcl.exprlong(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, int)

        self.assertRaises(TypeError, tcl.exprlong)
        self.assertRaises(TypeError, tcl.exprlong, "8.2", "+6")
        self.assertRaises(TypeError, tcl.exprlong, b"8.2 + 6")
        self.assertRaises(TclError, tcl.exprlong, "spam")
        check("", 0)
        check("8.2 + 6", 14)
        check("3.1 + $a", 6)
        check('2 + "$a.$b"', 5)
        check('4*[llength "6 2"]', 8)
        check('{word one} < "word $a"', 0)
        check("4*2 < 7", 0)
        check("hypot($a, 4)", 5)
        check("5 / 4", 1)
        check("5 / 4.0", 1)
        check('5 / ( [string length "abcd"] + 0.0 )', 1)
        check("20.0/5.0", 4)
        check('"0x03" > "2"', 1)
        check('[string length "a\xbd\u20ac"]', 3)
        check(r'[string length "a\xbd\u20ac"]', 3)
        self.assertRaises(TclError, tcl.exprlong, '"abc"')
        if tcl_version >= (8, 5):
            self.assertRaises(TclError, tcl.exprlong, "2**64")

    def test_exprboolean(self):
        tcl = self.interp
        tcl.call("set", "a", 3)
        tcl.call("set", "b", 6)

        def check(expr, expected):
            result = tcl.exprboolean(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, int)
            self.assertNotIsInstance(result, bool)

        self.assertRaises(TypeError, tcl.exprboolean)
        self.assertRaises(TypeError, tcl.exprboolean, "8.2", "+6")
        self.assertRaises(TypeError, tcl.exprboolean, b"8.2 + 6")
        self.assertRaises(TclError, tcl.exprboolean, "spam")
        check("", False)
        for value in ("0", "false", "no", "off"):
            check(value, False)
            check('"%s"' % value, False)
            check("{%s}" % value, False)
        for value in ("1", "true", "yes", "on"):
            check(value, True)
            check('"%s"' % value, True)
            check("{%s}" % value, True)
        check("8.2 + 6", True)
        check("3.1 + $a", True)
        check('2 + "$a.$b"', True)
        check('4*[llength "6 2"]', True)
        check('{word one} < "word $a"', False)
        check("4*2 < 7", False)
        check("hypot($a, 4)", True)
        check("5 / 4", True)
        check("5 / 4.0", True)
        check('5 / ( [string length "abcd"] + 0.0 )', True)
        check("20.0/5.0", True)
        check('"0x03" > "2"', True)
        check('[string length "a\xbd\u20ac"]', True)
        check(r'[string length "a\xbd\u20ac"]', True)
        self.assertRaises(TclError, tcl.exprboolean, '"abc"')
        if tcl_version >= (8, 5):
            check("2**64", True)

    def test_passing_values(self):
        def passValue(value):
            return self.interp.call("set", "_", value)

        self.assertEqual(passValue(True), True if self.wantobjects else "1")
        self.assertEqual(passValue(False), False if self.wantobjects else "0")
        self.assertEqual(passValue("string"), "string")
        self.assertEqual(passValue("string\u20ac"), "string\u20ac")
        self.assertEqual(passValue("str\x00ing"), "str\x00ing")
        self.assertEqual(passValue("str\x00ing\xbd"), "str\x00ing\xbd")
        self.assertEqual(passValue("str\x00ing\u20ac"), "str\x00ing\u20ac")
        self.assertEqual(passValue(b"str\x00ing"), "str\x00ing")
        self.assertEqual(passValue(b"str\xc0\x80ing"), "str\x00ing")
        for i in (0, 1, -1, 2 ** 31 - 1, -2 ** 31):
            self.assertEqual(passValue(i), i if self.wantobjects else str(i))
        for f in (
            0.0,
            1.0,
            -1.0,
            1 / 3,
            sys.float_info.min,
            sys.float_info.max,
            -sys.float_info.min,
            -sys.float_info.max,
        ):
            if self.wantobjects:
                self.assertEqual(passValue(f), f)
            else:
                self.assertEqual(float(passValue(f)), f)
        if self.wantobjects:
            f = passValue(float("nan"))
            self.assertNotEqual(f, f)
            self.assertEqual(passValue(float("inf")), float("inf"))
            self.assertEqual(passValue(-float("inf")), -float("inf"))
        else:
            f = float(passValue(float("nan")))
            self.assertNotEqual(f, f)
            self.assertEqual(float(passValue(float("inf"))), float("inf"))
            self.assertEqual(float(passValue(-float("inf"))), -float("inf"))
        self.assertEqual(passValue((1, "2", (3.4,))), (1, "2", (3.4,)) if self.wantobjects else "1 2 3.4")

    def test_user_command(self):
        result = None

        def testfunc(arg):
            nonlocal result
            result = arg
            return arg

        self.interp.createcommand("testfunc", testfunc)

        def check(value, expected, eq=self.assertEqual):
            r = self.interp.call("testfunc", value)
            self.assertIsInstance(result, str)
            eq(result, expected)
            self.assertIsInstance(r, str)
            eq(r, expected)

        def float_eq(actual, expected):
            expected = float(expected)
            self.assertAlmostEqual(float(actual), expected, delta=abs(expected) * 1e-10)

        def nan_eq(actual, expected):
            actual = float(actual)
            self.assertNotEqual(actual, actual)

        check(True, "1")
        check(False, "0")
        check("string", "string")
        check("string\xbd", "string\xbd")
        check("string\u20ac", "string\u20ac")
        check(b"string", "string")
        check(b"string\xe2\x82\xac", "string\u20ac")
        check("str\x00ing", "str\x00ing")
        check("str\x00ing\xbd", "str\x00ing\xbd")
        check("str\x00ing\u20ac", "str\x00ing\u20ac")
        check(b"str\xc0\x80ing", "str\x00ing")
        check(b"str\xc0\x80ing\xe2\x82\xac", "str\x00ing\u20ac")
        for i in (0, 1, -1, 2 ** 31 - 1, -2 ** 31):
            check(i, str(i))
        for f in (0.0, 1.0, -1.0):
            check(f, repr(f))
        for f in (1 / 3.0, sys.float_info.min, sys.float_info.max, -sys.float_info.min, -sys.float_info.max):
            check(f, f, eq=float_eq)
        check(float("inf"), "Inf", eq=float_eq)
        check(-float("inf"), "-Inf", eq=float_eq)
        check(float("nan"), "NaN", eq=nan_eq)
        check((), "")
        check((1, (2,), (3, 4), "5 6", ()), "1 2 {3 4} {5 6} {}")

    def test_splitlist(self):
        splitlist = self.interp.tk.splitlist
        call = self.interp.tk.call
        self.assertRaises(TypeError, splitlist)
        self.assertRaises(TypeError, splitlist, "a", "b")
        self.assertRaises(TypeError, splitlist, 2)
        testcases = [
            ("2", ("2",)),
            ("", ()),
            ("{}", ("",)),
            ('""', ("",)),
            ("a\n b\t\r c\n ", ("a", "b", "c")),
            (b"a\n b\t\r c\n ", ("a", "b", "c")),
            ("a \u20ac", ("a", "\u20ac")),
            (b"a \xe2\x82\xac", ("a", "\u20ac")),
            (b"a\xc0\x80b c\xc0\x80d", ("a\x00b", "c\x00d")),
            ("a {b c}", ("a", "b c")),
            (r"a b\ c", ("a", "b c")),
            (("a", "b c"), ("a", "b c")),
            ("a 2", ("a", "2")),
            (("a", 2), ("a", 2)),
            ("a 3.4", ("a", "3.4")),
            (("a", 3.4), ("a", 3.4)),
            ((), ()),
            (call("list", 1, "2", (3.4,)), (1, "2", (3.4,)) if self.wantobjects else ("1", "2", "3.4")),
        ]
        if tcl_version >= (8, 5):
            if not self.wantobjects or get_tk_patchlevel() < (8, 5, 5):
                # Before 8.5.5 dicts were converted to lists through string
                expected = ("12", "\u20ac", "\u20ac", "3.4")
            else:
                expected = (12, "\u20ac", "\u20ac", (3.4,))
            testcases += [(call("dict", "create", 12, "\u20ac", b"\xe2\x82\xac", (3.4,)), expected)]
        for arg, res in testcases:
            self.assertEqual(splitlist(arg), res, msg=arg)
        self.assertRaises(TclError, splitlist, "{")

    def test_split(self):
        split = self.interp.tk.split
        call = self.interp.tk.call
        self.assertRaises(TypeError, split)
        self.assertRaises(TypeError, split, "a", "b")
        self.assertRaises(TypeError, split, 2)
        testcases = [
            ("2", "2"),
            ("", ""),
            ("{}", ""),
            ('""', ""),
            ("{", "{"),
            ("a\n b\t\r c\n ", ("a", "b", "c")),
            (b"a\n b\t\r c\n ", ("a", "b", "c")),
            ("a \u20ac", ("a", "\u20ac")),
            (b"a \xe2\x82\xac", ("a", "\u20ac")),
            (b"a\xc0\x80b", "a\x00b"),
            (b"a\xc0\x80b c\xc0\x80d", ("a\x00b", "c\x00d")),
            (b"{a\xc0\x80b c\xc0\x80d", "{a\x00b c\x00d"),
            ("a {b c}", ("a", ("b", "c"))),
            (r"a b\ c", ("a", ("b", "c"))),
            (("a", b"b c"), ("a", ("b", "c"))),
            (("a", "b c"), ("a", ("b", "c"))),
            ("a 2", ("a", "2")),
            (("a", 2), ("a", 2)),
            ("a 3.4", ("a", "3.4")),
            (("a", 3.4), ("a", 3.4)),
            (("a", (2, 3.4)), ("a", (2, 3.4))),
            ((), ()),
            (call("list", 1, "2", (3.4,)), (1, "2", (3.4,)) if self.wantobjects else ("1", "2", "3.4")),
        ]
        if tcl_version >= (8, 5):
            if not self.wantobjects or get_tk_patchlevel() < (8, 5, 5):
                # Before 8.5.5 dicts were converted to lists through string
                expected = ("12", "\u20ac", "\u20ac", "3.4")
            else:
                expected = (12, "\u20ac", "\u20ac", (3.4,))
            testcases += [(call("dict", "create", 12, "\u20ac", b"\xe2\x82\xac", (3.4,)), expected)]
        for arg, res in testcases:
            self.assertEqual(split(arg), res, msg=arg)
Exemplo n.º 27
0
def setUpModule():
    if support.verbose:
        tcl = Tcl()
        print('patchlevel =', tcl.call('info', 'patchlevel'))
Exemplo n.º 28
0
class TclTest(unittest.TestCase):

    def setUp(self):
        self.interp = Tcl()
        self.wantobjects = self.interp.tk.wantobjects()

    def testEval(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.eval('set a'),'1')

    def test_eval_null_in_result(self):
        tcl = self.interp
        self.assertEqual(tcl.eval('set a "a\\0b"'), 'a\x00b')

    def testEvalException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'set a')

    def testEvalException2(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'this is wrong')

    def testCall(self):
        tcl = self.interp
        tcl.call('set','a','1')
        self.assertEqual(tcl.call('set','a'),'1')

    def testCallException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.call,'set','a')

    def testCallException2(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.call,'this','is','wrong')

    def testSetVar(self):
        tcl = self.interp
        tcl.setvar('a','1')
        self.assertEqual(tcl.eval('set a'),'1')

    def testSetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)','1')
        self.assertEqual(tcl.eval('set a(1)'),'1')

    def testGetVar(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.getvar('a'),'1')

    def testGetVarArray(self):
        tcl = self.interp
        tcl.eval('set a(1) 1')
        self.assertEqual(tcl.getvar('a(1)'),'1')

    def testGetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.getvar,'a')

    def testGetVarArrayException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.getvar,'a(1)')

    def testUnsetVar(self):
        tcl = self.interp
        tcl.setvar('a',1)
        self.assertEqual(tcl.eval('info exists a'),'1')
        tcl.unsetvar('a')
        self.assertEqual(tcl.eval('info exists a'),'0')

    def testUnsetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)',1)
        tcl.setvar('a(2)',2)
        self.assertEqual(tcl.eval('info exists a(1)'),'1')
        self.assertEqual(tcl.eval('info exists a(2)'),'1')
        tcl.unsetvar('a(1)')
        self.assertEqual(tcl.eval('info exists a(1)'),'0')
        self.assertEqual(tcl.eval('info exists a(2)'),'1')

    def testUnsetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.unsetvar,'a')

    def testEvalFile(self):
        tcl = self.interp
        with open(support.TESTFN, 'w') as f:
            self.addCleanup(support.unlink, support.TESTFN)
            f.write("""set a 1
            set b 2
            set c [ expr $a + $b ]
            """)
        tcl.evalfile(support.TESTFN)
        self.assertEqual(tcl.eval('set a'),'1')
        self.assertEqual(tcl.eval('set b'),'2')
        self.assertEqual(tcl.eval('set c'),'3')

    def test_evalfile_null_in_result(self):
        tcl = self.interp
        with open(support.TESTFN, 'w') as f:
            self.addCleanup(support.unlink, support.TESTFN)
            f.write("""
            set a "a\0b"
            set b "a\\0b"
            """)
        tcl.evalfile(support.TESTFN)
        self.assertEqual(tcl.eval('set a'), 'a\x00b')
        self.assertEqual(tcl.eval('set b'), 'a\x00b')

    def testEvalFileException(self):
        tcl = self.interp
        filename = "doesnotexists"
        try:
            os.remove(filename)
        except Exception as e:
            pass
        self.assertRaises(TclError,tcl.evalfile,filename)

    def testPackageRequireException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'package require DNE')

    @unittest.skipUnless(sys.platform == 'win32', 'Requires Windows')
    def testLoadWithUNC(self):
        # Build a UNC path from the regular path.
        # Something like
        #   \\%COMPUTERNAME%\c$\python27\python.exe

        fullname = os.path.abspath(sys.executable)
        if fullname[1] != ':':
            raise unittest.SkipTest('Absolute path should have drive part')
        unc_name = r'\\%s\%s$\%s' % (os.environ['COMPUTERNAME'],
                                    fullname[0],
                                    fullname[3:])
        if not os.path.exists(unc_name):
            raise unittest.SkipTest('Cannot connect to UNC Path')

        with support.EnvironmentVarGuard() as env:
            env.unset("TCL_LIBRARY")
            f = os.popen('%s -c "import tkinter; print(tkinter)"' % (unc_name,))

        self.assertIn('tkinter', f.read())
        # exit code must be zero
        self.assertEqual(f.close(), None)

    def test_exprstring(self):
        tcl = self.interp
        tcl.call('set', 'a', 3)
        tcl.call('set', 'b', 6)
        def check(expr, expected):
            result = tcl.exprstring(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, str)

        self.assertRaises(TypeError, tcl.exprstring)
        self.assertRaises(TypeError, tcl.exprstring, '8.2', '+6')
        self.assertRaises(TypeError, tcl.exprstring, b'8.2 + 6')
        self.assertRaises(TclError, tcl.exprstring, 'spam')
        check('', '0')
        check('8.2 + 6', '14.2')
        check('3.1 + $a', '6.1')
        check('2 + "$a.$b"', '5.6')
        check('4*[llength "6 2"]', '8')
        check('{word one} < "word $a"', '0')
        check('4*2 < 7', '0')
        check('hypot($a, 4)', '5.0')
        check('5 / 4', '1')
        check('5 / 4.0', '1.25')
        check('5 / ( [string length "abcd"] + 0.0 )', '1.25')
        check('20.0/5.0', '4.0')
        check('"0x03" > "2"', '1')
        check('[string length "a\xbd\u20ac"]', '3')
        check(r'[string length "a\xbd\u20ac"]', '3')
        check('"abc"', 'abc')
        check('"a\xbd\u20ac"', 'a\xbd\u20ac')
        check(r'"a\xbd\u20ac"', 'a\xbd\u20ac')
        check(r'"a\0b"', 'a\x00b')
        if tcl_version >= (8, 5):
            check('2**64', str(2**64))

    def test_exprdouble(self):
        tcl = self.interp
        tcl.call('set', 'a', 3)
        tcl.call('set', 'b', 6)
        def check(expr, expected):
            result = tcl.exprdouble(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, float)

        self.assertRaises(TypeError, tcl.exprdouble)
        self.assertRaises(TypeError, tcl.exprdouble, '8.2', '+6')
        self.assertRaises(TypeError, tcl.exprdouble, b'8.2 + 6')
        self.assertRaises(TclError, tcl.exprdouble, 'spam')
        check('', 0.0)
        check('8.2 + 6', 14.2)
        check('3.1 + $a', 6.1)
        check('2 + "$a.$b"', 5.6)
        check('4*[llength "6 2"]', 8.0)
        check('{word one} < "word $a"', 0.0)
        check('4*2 < 7', 0.0)
        check('hypot($a, 4)', 5.0)
        check('5 / 4', 1.0)
        check('5 / 4.0', 1.25)
        check('5 / ( [string length "abcd"] + 0.0 )', 1.25)
        check('20.0/5.0', 4.0)
        check('"0x03" > "2"', 1.0)
        check('[string length "a\xbd\u20ac"]', 3.0)
        check(r'[string length "a\xbd\u20ac"]', 3.0)
        self.assertRaises(TclError, tcl.exprdouble, '"abc"')
        if tcl_version >= (8, 5):
            check('2**64', float(2**64))

    def test_exprlong(self):
        tcl = self.interp
        tcl.call('set', 'a', 3)
        tcl.call('set', 'b', 6)
        def check(expr, expected):
            result = tcl.exprlong(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, int)

        self.assertRaises(TypeError, tcl.exprlong)
        self.assertRaises(TypeError, tcl.exprlong, '8.2', '+6')
        self.assertRaises(TypeError, tcl.exprlong, b'8.2 + 6')
        self.assertRaises(TclError, tcl.exprlong, 'spam')
        check('', 0)
        check('8.2 + 6', 14)
        check('3.1 + $a', 6)
        check('2 + "$a.$b"', 5)
        check('4*[llength "6 2"]', 8)
        check('{word one} < "word $a"', 0)
        check('4*2 < 7', 0)
        check('hypot($a, 4)', 5)
        check('5 / 4', 1)
        check('5 / 4.0', 1)
        check('5 / ( [string length "abcd"] + 0.0 )', 1)
        check('20.0/5.0', 4)
        check('"0x03" > "2"', 1)
        check('[string length "a\xbd\u20ac"]', 3)
        check(r'[string length "a\xbd\u20ac"]', 3)
        self.assertRaises(TclError, tcl.exprlong, '"abc"')
        if tcl_version >= (8, 5):
            self.assertRaises(TclError, tcl.exprlong, '2**64')

    def test_exprboolean(self):
        tcl = self.interp
        tcl.call('set', 'a', 3)
        tcl.call('set', 'b', 6)
        def check(expr, expected):
            result = tcl.exprboolean(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, int)
            self.assertNotIsInstance(result, bool)

        self.assertRaises(TypeError, tcl.exprboolean)
        self.assertRaises(TypeError, tcl.exprboolean, '8.2', '+6')
        self.assertRaises(TypeError, tcl.exprboolean, b'8.2 + 6')
        self.assertRaises(TclError, tcl.exprboolean, 'spam')
        check('', False)
        for value in ('0', 'false', 'no', 'off'):
            check(value, False)
            check('"%s"' % value, False)
            check('{%s}' % value, False)
        for value in ('1', 'true', 'yes', 'on'):
            check(value, True)
            check('"%s"' % value, True)
            check('{%s}' % value, True)
        check('8.2 + 6', True)
        check('3.1 + $a', True)
        check('2 + "$a.$b"', True)
        check('4*[llength "6 2"]', True)
        check('{word one} < "word $a"', False)
        check('4*2 < 7', False)
        check('hypot($a, 4)', True)
        check('5 / 4', True)
        check('5 / 4.0', True)
        check('5 / ( [string length "abcd"] + 0.0 )', True)
        check('20.0/5.0', True)
        check('"0x03" > "2"', True)
        check('[string length "a\xbd\u20ac"]', True)
        check(r'[string length "a\xbd\u20ac"]', True)
        self.assertRaises(TclError, tcl.exprboolean, '"abc"')
        if tcl_version >= (8, 5):
            check('2**64', True)

    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)

        self.assertEqual(passValue(True), True if self.wantobjects else '1')
        self.assertEqual(passValue(False), False if self.wantobjects else '0')
        self.assertEqual(passValue('string'), 'string')
        self.assertEqual(passValue('string\u20ac'), 'string\u20ac')
        self.assertEqual(passValue('str\x00ing'), 'str\x00ing')
        self.assertEqual(passValue('str\x00ing\xbd'), 'str\x00ing\xbd')
        self.assertEqual(passValue('str\x00ing\u20ac'), 'str\x00ing\u20ac')
        self.assertEqual(passValue(b'str\x00ing'), 'str\x00ing')
        self.assertEqual(passValue(b'str\xc0\x80ing'), 'str\x00ing')
        for i in (0, 1, -1, 2**31-1, -2**31):
            self.assertEqual(passValue(i), i if self.wantobjects else str(i))
        for f in (0.0, 1.0, -1.0, 1/3,
                  sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            if self.wantobjects:
                self.assertEqual(passValue(f), f)
            else:
                self.assertEqual(float(passValue(f)), f)
        if self.wantobjects:
            f = passValue(float('nan'))
            self.assertNotEqual(f, f)
            self.assertEqual(passValue(float('inf')), float('inf'))
            self.assertEqual(passValue(-float('inf')), -float('inf'))
        else:
            f = float(passValue(float('nan')))
            self.assertNotEqual(f, f)
            self.assertEqual(float(passValue(float('inf'))), float('inf'))
            self.assertEqual(float(passValue(-float('inf'))), -float('inf'))
        self.assertEqual(passValue((1, '2', (3.4,))),
                         (1, '2', (3.4,)) if self.wantobjects else '1 2 3.4')

    def test_user_command(self):
        result = None
        def testfunc(arg):
            nonlocal result
            result = arg
            return arg
        self.interp.createcommand('testfunc', testfunc)
        self.addCleanup(self.interp.tk.deletecommand, 'testfunc')
        def check(value, expected, eq=self.assertEqual):
            r = self.interp.call('testfunc', value)
            self.assertIsInstance(result, str)
            eq(result, expected)
            self.assertIsInstance(r, str)
            eq(r, expected)
        def float_eq(actual, expected):
            expected = float(expected)
            self.assertAlmostEqual(float(actual), expected,
                                   delta=abs(expected) * 1e-10)
        def nan_eq(actual, expected):
            actual = float(actual)
            self.assertNotEqual(actual, actual)

        check(True, '1')
        check(False, '0')
        check('string', 'string')
        check('string\xbd', 'string\xbd')
        check('string\u20ac', 'string\u20ac')
        check(b'string', 'string')
        check(b'string\xe2\x82\xac', 'string\u20ac')
        check('str\x00ing', 'str\x00ing')
        check('str\x00ing\xbd', 'str\x00ing\xbd')
        check('str\x00ing\u20ac', 'str\x00ing\u20ac')
        check(b'str\xc0\x80ing', 'str\x00ing')
        check(b'str\xc0\x80ing\xe2\x82\xac', 'str\x00ing\u20ac')
        for i in (0, 1, -1, 2**31-1, -2**31):
            check(i, str(i))
        for f in (0.0, 1.0, -1.0):
            check(f, repr(f))
        for f in (1/3.0, sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            check(f, f, eq=float_eq)
        check(float('inf'), 'Inf', eq=float_eq)
        check(-float('inf'), '-Inf', eq=float_eq)
        check(float('nan'), 'NaN', eq=nan_eq)
        check((), '')
        check((1, (2,), (3, 4), '5 6', ()), '1 2 {3 4} {5 6} {}')

    def test_splitlist(self):
        splitlist = self.interp.tk.splitlist
        call = self.interp.tk.call
        self.assertRaises(TypeError, splitlist)
        self.assertRaises(TypeError, splitlist, 'a', 'b')
        self.assertRaises(TypeError, splitlist, 2)
        testcases = [
            ('2', ('2',)),
            ('', ()),
            ('{}', ('',)),
            ('""', ('',)),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (b'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \u20ac', ('a', '\u20ac')),
            (b'a \xe2\x82\xac', ('a', '\u20ac')),
            (b'a\xc0\x80b c\xc0\x80d', ('a\x00b', 'c\x00d')),
            ('a {b c}', ('a', 'b c')),
            (r'a b\ c', ('a', 'b c')),
            (('a', 'b c'), ('a', 'b c')),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            ((), ()),
            (call('list', 1, '2', (3.4,)),
                (1, '2', (3.4,)) if self.wantobjects else
                ('1', '2', '3.4')),
        ]
        if tcl_version >= (8, 5):
            if not self.wantobjects or get_tk_patchlevel() < (8, 5, 5):
                # Before 8.5.5 dicts were converted to lists through string
                expected = ('12', '\u20ac', '\u20ac', '3.4')
            else:
                expected = (12, '\u20ac', '\u20ac', (3.4,))
            testcases += [
                (call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac', (3.4,)),
                    expected),
            ]
        for arg, res in testcases:
            self.assertEqual(splitlist(arg), res, msg=arg)
        self.assertRaises(TclError, splitlist, '{')

    def test_split(self):
        split = self.interp.tk.split
        call = self.interp.tk.call
        self.assertRaises(TypeError, split)
        self.assertRaises(TypeError, split, 'a', 'b')
        self.assertRaises(TypeError, split, 2)
        testcases = [
            ('2', '2'),
            ('', ''),
            ('{}', ''),
            ('""', ''),
            ('{', '{'),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (b'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \u20ac', ('a', '\u20ac')),
            (b'a \xe2\x82\xac', ('a', '\u20ac')),
            (b'a\xc0\x80b', 'a\x00b'),
            (b'a\xc0\x80b c\xc0\x80d', ('a\x00b', 'c\x00d')),
            (b'{a\xc0\x80b c\xc0\x80d', '{a\x00b c\x00d'),
            ('a {b c}', ('a', ('b', 'c'))),
            (r'a b\ c', ('a', ('b', 'c'))),
            (('a', b'b c'), ('a', ('b', 'c'))),
            (('a', 'b c'), ('a', ('b', 'c'))),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            (('a', (2, 3.4)), ('a', (2, 3.4))),
            ((), ()),
            (call('list', 1, '2', (3.4,)),
                (1, '2', (3.4,)) if self.wantobjects else
                ('1', '2', '3.4')),
        ]
        if tcl_version >= (8, 5):
            if not self.wantobjects or get_tk_patchlevel() < (8, 5, 5):
                # Before 8.5.5 dicts were converted to lists through string
                expected = ('12', '\u20ac', '\u20ac', '3.4')
            else:
                expected = (12, '\u20ac', '\u20ac', (3.4,))
            testcases += [
                (call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac', (3.4,)),
                    expected),
            ]
        for arg, res in testcases:
            self.assertEqual(split(arg), res, msg=arg)

    def test_merge(self):
        with support.check_warnings(('merge is deprecated',
                                     DeprecationWarning)):
            merge = self.interp.tk.merge
            call = self.interp.tk.call
            testcases = [
                ((), ''),
                (('a',), 'a'),
                ((2,), '2'),
                (('',), '{}'),
                ('{', '\\{'),
                (('a', 'b', 'c'), 'a b c'),
                ((' ', '\t', '\r', '\n'), '{ } {\t} {\r} {\n}'),
                (('a', ' ', 'c'), 'a { } c'),
                (('a', '€'), 'a €'),
                (('a', '\U000104a2'), 'a \U000104a2'),
                (('a', b'\xe2\x82\xac'), 'a €'),
                (('a', ('b', 'c')), 'a {b c}'),
                (('a', 2), 'a 2'),
                (('a', 3.4), 'a 3.4'),
                (('a', (2, 3.4)), 'a {2 3.4}'),
                ((), ''),
                ((call('list', 1, '2', (3.4,)),), '{1 2 3.4}'),
            ]
            if tcl_version >= (8, 5):
                testcases += [
                    ((call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac', (3.4,)),),
                     '{12 € € 3.4}'),
                ]
            for args, res in testcases:
                self.assertEqual(merge(*args), res, msg=args)
            self.assertRaises(UnicodeDecodeError, merge, b'\x80')
            self.assertRaises(UnicodeEncodeError, merge, '\udc80')
Exemplo n.º 29
0
 def setUp(self):
     self.root = Tcl()
Exemplo n.º 30
0
 def testLoadTk(self):
     tcl = Tcl()
     self.assertRaises(TclError,tcl.winfo_geometry)
     tcl.loadtk()
     self.assertEqual('1x1+0+0', tcl.winfo_geometry())
     tcl.destroy()
Exemplo n.º 31
0
        i += 1

    return id_to_labels, labels_to_id


print("\n")

label_file = 'output_labels_alphabet.txt'
id_to_labels, labels_to_id = load_label_dicts(label_file)

files = []
crop_folder_path = os.path.join('crop')
path = os.path.join(crop_folder_path, "*.png")
frames = glob.glob(path)
files = frames
files = list(Tcl().call('lsort', '-dict', files))

prediction_vector = get_inference_vector_one_frame_alphabet(files)
prediction_vector = np.array(prediction_vector)

print("\n")

l = []
for i in range(prediction_vector.shape[0]):
    l.append(id_to_labels[np.argmax(prediction_vector[i])])
print("Labels from Cropped images")
print(l)

files = []
data_folder_path = os.path.join('data')
path = os.path.join(data_folder_path, "*.png")
Exemplo n.º 32
0
class c_mainFrame(Tk):
    """
    classdocs
    """

    def __init__(self, **paras):
        """
        Constructor
        """
        try:
            super().__init__(**paras)

            self.__check_enviroment()
            self.system = self.tk.call("tk", "windowingsystem")

            self.__mystyle()
            self.__setup()
            self.__create_children()
            pass
        except:
            raise
        else:
            pass

    def __del__(self):
        try:
            pass
        except:
            pass
        else:
            pass

    def __check_enviroment(self):
        try:
            self.py_Version = platform.python_version()
            self.py_Compiler = platform.python_compiler()
            self.py_Build = platform.python_build()

            major, minor, patch = self.py_Version.split(".")
            if (int(major) < MIN_PY_MAJOR_VERSION) or (
                (int(major) == MIN_PY_MAJOR_VERSION) and (int(minor) < MIN_PY_MINOR_VERSION)
            ):
                raise Exception(
                    "Python Version " + MIN_TCL_MAJOR_VERSION + "." + MIN_TCL_MINOR_VERSION + ".x or higher required"
                )

            self.tcl_Version = Tcl().eval("info patchlevel")
            major, minor, patch = self.tcl_Version.split(".")
            if (int(major) < MIN_TCL_MAJOR_VERSION) or (
                (int(major) == MIN_TCL_MAJOR_VERSION) and (int(minor) < MIN_TCL_MINOR_VERSION)
            ):
                raise Exception(
                    "TCL Version " + MIN_TCL_MAJOR_VERSION + "." + MIN_TCL_MINOR_VERSION + ".x or higher required"
                )
        except:
            raise

    def __setup(self):
        try:
            self.option_add("*tearOFF", FALSE)
            self.geometry("1024x640+10+10")
            self.configure(title="Extended PTC Gateway")

            pass
        except:
            pass
        else:
            pass

    def __create_children(self):
        try:
            self.__create_menue()
            pass
        except:
            raise
        else:
            pass

    def __create_menue(self):
        try:
            self.frm_menu = ttk.Frame(self, name="menu")

            ttk.Button(self.frm_menu, name="btn_new_file", text="New", command=self.__on_menu_new_file).pack(side=LEFT)
            ttk.Button(self.frm_menu, name="btn_open_file", text="Open", command=self.__on_menu_open_file).pack(
                side=LEFT
            )
            ttk.Button(
                self.frm_menu, name="btn_save_file", text="Save", state="disabled", command=self.__on_menu_save_file
            ).pack(side=LEFT)
            ttk.Button(
                self.frm_menu,
                name="btn_save_as_file",
                text="SaveAs",
                state="disabled",
                command=self.__on_menu_save_as_file,
            ).pack(side=LEFT)

            self.frm_menu.pack(side=TOP, fill=X)
            pass
        except:
            raise
        else:
            pass

    def __create_client(self, savedata=None):
        try:
            try:
                self.frm_client.destroy()
            except:
                pass
            self.frm_client = c_clientFrame(self, savedata=savedata, name="client")
            self.frm_client.pack(side=TOP, fill=BOTH, expand=True)
            self.__save_enable()
            pass
        except:
            raise

    def __on_menu_open_file(self):
        try:
            filename = filedialog.askopenfilename(
                filetypes=[("ExtGatewayConfig", SAVE_FILE_ENDING)], title="Select Configuration File"
            )
            if filename:
                self.__load(filename)
            pass
        except:
            raise

    def __on_menu_new_file(self):
        try:
            self.__create_client()
            pass
        except:
            raise

    def __on_menu_save_file(self):
        try:
            self.__save(self.filename)
            pass
        except:
            self.__on_menu_save_as_file()

    def __on_menu_save_as_file(self):
        try:
            filename = filedialog.asksaveasfilename(
                filetypes=[("ExtGatewayConfig", SAVE_FILE_ENDING)], title="Select Configuration File"
            )
            if filename:
                if filename[-len(SAVE_FILE_ENDING) :] != SAVE_FILE_ENDING:
                    filename += SAVE_FILE_ENDING
                self.__save(filename)
            pass
        except:
            raise

    def cbk_menue_disable(self):
        try:
            self.children["menu"].children["btn_save_file"].config(state="disabled")
            self.children["menu"].children["btn_save_as_file"].config(state="disabled")
            self.children["menu"].children["btn_new_file"].config(state="disabled")
            self.children["menu"].children["btn_open_file"].config(state="disabled")
            pass
        except:
            raise

    def cbk_menue_enable(self):
        try:
            self.children["menu"].children["btn_save_file"].config(state="normal")
            self.children["menu"].children["btn_save_as_file"].config(state="normal")
            self.children["menu"].children["btn_new_file"].config(state="normal")
            self.children["menu"].children["btn_open_file"].config(state="normal")
            pass
        except:
            raise

    def __save_enable(self):
        self.children["menu"].children["btn_save_file"].config(state="normal")
        self.children["menu"].children["btn_save_as_file"].config(state="normal")

    def __get_save_data(self):
        return self.frm_client.get_save_data()

    def __restore_data(self, savedata):
        self.__create_client(savedata)
        pass

    def __save(self, filename):
        try:
            savedata = self.__get_save_data()
            self.filename = filename
            f = open(filename, mode="wb")
            s = pickle.dumps(savedata)
            f.write(s)
            f.close()
            pass
        except:
            raise

    def __load(self, filename):
        try:
            self.filename = filename
            f = open(filename, mode="rb")
            s = f.read()
            f.close()
            savedata = pickle.loads(s)
            self.__restore_data(savedata)
            pass
        except:
            raise

    def __mystyle(self):
        self.style = ttk.Style()

        self.style.configure("TFrame", padding=5, relief=RIDGE)
        self.style.configure("TButton", padding=3, relief=FLAT, padx=2, pady=2)
        self.style.configure("TLable", padding=2, relief=FLAT, padx=2, pady=2)

        self.style.configure("TEntry", padding=2, relief=RIDGE, padx=2, pady=2)
        self.style.configure("TCheckbutton", padding=2, relief=RIDGE, padx=2, pady=2)

        self.style.configure(
            "ok.TEntry", foreground="green", background="green", padding=3, relief=RIDGE, padx=2, pady=2
        )
        self.style.configure("err.TEntry", foreground="red", background="red", padding=3, relief=RIDGE, padx=2, pady=2)
        self.style.configure(
            "tbd.TButton", foreground="gray", background="gray", padding=3, relief=FLAT, padx=2, pady=2
        )
        self.style.configure(
            "warn.TButton", foreground="yellow", background="yellow", padding=3, relief=FLAT, padx=2, pady=2
        )
        self.style.configure(
            "ok.TButton", foreground="green", background="green", padding=3, relief=FLAT, padx=2, pady=2
        )
        self.style.configure("err.TButton", foreground="red", background="red", padding=3, relief=FLAT, padx=2, pady=2)
        self.style.configure(
            "option.TButton", foreground="blue", background="blue", padding=3, relief=FLAT, padx=2, pady=2
        )
Exemplo n.º 33
0
def setUpModule():
    if support.verbose:
        tcl = Tcl()
        print("patchlevel =", tcl.call("info", "patchlevel"))
Exemplo n.º 34
0
 def setUp(self):
     self.interp = Tcl()
     self.wantobjects = self.interp.tk.wantobjects()
Exemplo n.º 35
0
def setUpModule():
    if support.verbose:
        tcl = Tcl()
        print('patchlevel =', tcl.call('info', 'patchlevel'))
import os
import shutil
from tkinter import Tcl

m = 50000
n = 5000

src_dir = "C:/Users/shubh/Downloads/Shubh_mypy_proj/comp_vision/train/traintemp"
dst_dir = "C:/Users/shubh/Desktop/thisone"
file_list = os.listdir(src_dir)
file_list = (Tcl().call('lsort', '-dict', file_list))

for i in range(0, m, n):
    for j in range(i, i + 100):
        shutil.copy(file_list[j], dst_dir)
Exemplo n.º 37
0
class TclTest(unittest.TestCase):
    def setUp(self):
        self.interp = Tcl()

    def testEval(self):
        tcl = self.interp
        tcl.eval("set a 1")
        self.assertEqual(tcl.eval("set a"), "1")

    def testEvalException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.eval, "set a")

    def testEvalException2(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.eval, "this is wrong")

    def testCall(self):
        tcl = self.interp
        tcl.call("set", "a", "1")
        self.assertEqual(tcl.call("set", "a"), "1")

    def testCallException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.call, "set", "a")

    def testCallException2(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.call, "this", "is", "wrong")

    def testSetVar(self):
        tcl = self.interp
        tcl.setvar("a", "1")
        self.assertEqual(tcl.eval("set a"), "1")

    def testSetVarArray(self):
        tcl = self.interp
        tcl.setvar("a(1)", "1")
        self.assertEqual(tcl.eval("set a(1)"), "1")

    def testGetVar(self):
        tcl = self.interp
        tcl.eval("set a 1")
        self.assertEqual(tcl.getvar("a"), "1")

    def testGetVarArray(self):
        tcl = self.interp
        tcl.eval("set a(1) 1")
        self.assertEqual(tcl.getvar("a(1)"), "1")

    def testGetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.getvar, "a")

    def testGetVarArrayException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.getvar, "a(1)")

    def testUnsetVar(self):
        tcl = self.interp
        tcl.setvar("a", 1)
        self.assertEqual(tcl.eval("info exists a"), "1")
        tcl.unsetvar("a")
        self.assertEqual(tcl.eval("info exists a"), "0")

    def testUnsetVarArray(self):
        tcl = self.interp
        tcl.setvar("a(1)", 1)
        tcl.setvar("a(2)", 2)
        self.assertEqual(tcl.eval("info exists a(1)"), "1")
        self.assertEqual(tcl.eval("info exists a(2)"), "1")
        tcl.unsetvar("a(1)")
        self.assertEqual(tcl.eval("info exists a(1)"), "0")
        self.assertEqual(tcl.eval("info exists a(2)"), "1")

    def testUnsetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.unsetvar, "a")

    def testEvalFile(self):
        tcl = self.interp
        filename = "testEvalFile.tcl"
        fd = open(filename, "w")
        script = """set a 1
        set b 2
        set c [ expr $a + $b ]
        """
        fd.write(script)
        fd.close()
        tcl.evalfile(filename)
        os.remove(filename)
        self.assertEqual(tcl.eval("set a"), "1")
        self.assertEqual(tcl.eval("set b"), "2")
        self.assertEqual(tcl.eval("set c"), "3")

    def testEvalFileException(self):
        tcl = self.interp
        filename = "doesnotexists"
        try:
            os.remove(filename)
        except Exception as e:
            pass
        self.assertRaises(TclError, tcl.evalfile, filename)

    def testPackageRequireException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.eval, "package require DNE")

    @unittest.skipUnless(sys.platform == "win32", "Requires Windows")
    def testLoadWithUNC(self):
        # Build a UNC path from the regular path.
        # Something like
        #   \\%COMPUTERNAME%\c$\python27\python.exe

        fullname = os.path.abspath(sys.executable)
        if fullname[1] != ":":
            raise unittest.SkipTest("Absolute path should have drive part")
        unc_name = r"\\%s\%s$\%s" % (os.environ["COMPUTERNAME"], fullname[0], fullname[3:])
        if not os.path.exists(unc_name):
            raise unittest.SkipTest("Cannot connect to UNC Path")

        with support.EnvironmentVarGuard() as env:
            env.unset("TCL_LIBRARY")
            f = os.popen('%s -c "import tkinter; print(tkinter)"' % (unc_name,))

        self.assertIn("tkinter", f.read())
        # exit code must be zero
        self.assertEqual(f.close(), None)

    def test_passing_values(self):
        def passValue(value):
            return self.interp.call("set", "_", value)

        self.assertEqual(passValue(True), True)
        self.assertEqual(passValue(False), False)
        self.assertEqual(passValue("string"), "string")
        self.assertEqual(passValue("string\u20ac"), "string\u20ac")
        for i in (0, 1, -1, 2 ** 31 - 1, -2 ** 31):
            self.assertEqual(passValue(i), i)
        for f in (
            0.0,
            1.0,
            -1.0,
            1 / 3,
            sys.float_info.min,
            sys.float_info.max,
            -sys.float_info.min,
            -sys.float_info.max,
        ):
            self.assertEqual(passValue(f), f)
        for f in float("nan"), float("inf"), -float("inf"):
            if f != f:  # NaN
                self.assertNotEqual(passValue(f), f)
            else:
                self.assertEqual(passValue(f), f)
        self.assertEqual(passValue((1, "2", (3.4,))), (1, "2", (3.4,)))

    def test_splitlist(self):
        splitlist = self.interp.tk.splitlist
        call = self.interp.tk.call
        self.assertRaises(TypeError, splitlist)
        self.assertRaises(TypeError, splitlist, "a", "b")
        self.assertRaises(TypeError, splitlist, 2)
        testcases = [
            ("2", ("2",)),
            ("", ()),
            ("{}", ("",)),
            ('""', ("",)),
            ("a\n b\t\r c\n ", ("a", "b", "c")),
            (b"a\n b\t\r c\n ", ("a", "b", "c")),
            ("a \u20ac", ("a", "\u20ac")),
            (b"a \xe2\x82\xac", ("a", "\u20ac")),
            ("a {b c}", ("a", "b c")),
            (r"a b\ c", ("a", "b c")),
            (("a", "b c"), ("a", "b c")),
            ("a 2", ("a", "2")),
            (("a", 2), ("a", 2)),
            ("a 3.4", ("a", "3.4")),
            (("a", 3.4), ("a", 3.4)),
            ((), ()),
            (call("list", 1, "2", (3.4,)), (1, "2", (3.4,))),
        ]
        if tcl_version >= (8, 5):
            testcases += [
                (call("dict", "create", 1, "\u20ac", b"\xe2\x82\xac", (3.4,)), (1, "\u20ac", "\u20ac", (3.4,)))
            ]
        for arg, res in testcases:
            self.assertEqual(splitlist(arg), res, msg=arg)
        self.assertRaises(TclError, splitlist, "{")

    def test_split(self):
        split = self.interp.tk.split
        call = self.interp.tk.call
        self.assertRaises(TypeError, split)
        self.assertRaises(TypeError, split, "a", "b")
        self.assertRaises(TypeError, split, 2)
        testcases = [
            ("2", "2"),
            ("", ""),
            ("{}", ""),
            ('""', ""),
            ("{", "{"),
            ("a\n b\t\r c\n ", ("a", "b", "c")),
            (b"a\n b\t\r c\n ", ("a", "b", "c")),
            ("a \u20ac", ("a", "\u20ac")),
            (b"a \xe2\x82\xac", ("a", "\u20ac")),
            ("a {b c}", ("a", ("b", "c"))),
            (r"a b\ c", ("a", ("b", "c"))),
            (("a", b"b c"), ("a", ("b", "c"))),
            (("a", "b c"), ("a", ("b", "c"))),
            ("a 2", ("a", "2")),
            (("a", 2), ("a", 2)),
            ("a 3.4", ("a", "3.4")),
            (("a", 3.4), ("a", 3.4)),
            (("a", (2, 3.4)), ("a", (2, 3.4))),
            ((), ()),
            (call("list", 1, "2", (3.4,)), (1, "2", (3.4,))),
        ]
        if tcl_version >= (8, 5):
            testcases += [
                (call("dict", "create", 12, "\u20ac", b"\xe2\x82\xac", (3.4,)), (12, "\u20ac", "\u20ac", (3.4,)))
            ]
        for arg, res in testcases:
            self.assertEqual(split(arg), res, msg=arg)
Exemplo n.º 38
0
class TclTest(unittest.TestCase):

    def setUp(self):
        self.interp = Tcl()
        self.wantobjects = self.interp.tk.wantobjects()

    def testEval(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.eval('set a'),'1')

    def test_eval_null_in_result(self):
        tcl = self.interp
        self.assertEqual(tcl.eval('set a "a\\0b"'), 'a\x00b')

    def testEvalException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'set a')

    def testEvalException2(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'this is wrong')

    def testCall(self):
        tcl = self.interp
        tcl.call('set','a','1')
        self.assertEqual(tcl.call('set','a'),'1')

    def testCallException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.call,'set','a')

    def testCallException2(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.call,'this','is','wrong')

    def testSetVar(self):
        tcl = self.interp
        tcl.setvar('a','1')
        self.assertEqual(tcl.eval('set a'),'1')

    def testSetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)','1')
        self.assertEqual(tcl.eval('set a(1)'),'1')

    def testGetVar(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.getvar('a'),'1')

    def testGetVarArray(self):
        tcl = self.interp
        tcl.eval('set a(1) 1')
        self.assertEqual(tcl.getvar('a(1)'),'1')

    def testGetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.getvar,'a')

    def testGetVarArrayException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.getvar,'a(1)')

    def testUnsetVar(self):
        tcl = self.interp
        tcl.setvar('a',1)
        self.assertEqual(tcl.eval('info exists a'),'1')
        tcl.unsetvar('a')
        self.assertEqual(tcl.eval('info exists a'),'0')

    def testUnsetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)',1)
        tcl.setvar('a(2)',2)
        self.assertEqual(tcl.eval('info exists a(1)'),'1')
        self.assertEqual(tcl.eval('info exists a(2)'),'1')
        tcl.unsetvar('a(1)')
        self.assertEqual(tcl.eval('info exists a(1)'),'0')
        self.assertEqual(tcl.eval('info exists a(2)'),'1')

    def testUnsetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.unsetvar,'a')

    def get_integers(self):
        integers = (0, 1, -1, 2**31-1, -2**31, 2**31, -2**31-1, 2**63-1, -2**63)
        # bignum was added in Tcl 8.5, but its support is able only since 8.5.8
        if (get_tk_patchlevel() >= (8, 6, 0, 'final') or
            (8, 5, 8) <= get_tk_patchlevel() < (8, 6)):
            integers += (2**63, -2**63-1, 2**1000, -2**1000)
        return integers

    def test_getint(self):
        tcl = self.interp.tk
        for i in self.get_integers():
            self.assertEqual(tcl.getint(' %d ' % i), i)
            if tcl_version >= (8, 5):
                self.assertEqual(tcl.getint(' %#o ' % i), i)
            self.assertEqual(tcl.getint((' %#o ' % i).replace('o', '')), i)
            self.assertEqual(tcl.getint(' %#x ' % i), i)
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            self.assertRaises(TclError, tcl.getint, str(2**1000))
        self.assertEqual(tcl.getint(42), 42)
        self.assertRaises(TypeError, tcl.getint)
        self.assertRaises(TypeError, tcl.getint, '42', '10')
        self.assertRaises(TypeError, tcl.getint, b'42')
        self.assertRaises(TypeError, tcl.getint, 42.0)
        self.assertRaises(TclError, tcl.getint, 'a')
        self.assertRaises((TypeError, ValueError, TclError),
                          tcl.getint, '42\0')
        self.assertRaises((UnicodeEncodeError, ValueError, TclError),
                          tcl.getint, '42\ud800')

    def test_getdouble(self):
        tcl = self.interp.tk
        self.assertEqual(tcl.getdouble(' 42 '), 42.0)
        self.assertEqual(tcl.getdouble(' 42.5 '), 42.5)
        self.assertEqual(tcl.getdouble(42.5), 42.5)
        self.assertEqual(tcl.getdouble(42), 42.0)
        self.assertRaises(TypeError, tcl.getdouble)
        self.assertRaises(TypeError, tcl.getdouble, '42.5', '10')
        self.assertRaises(TypeError, tcl.getdouble, b'42.5')
        self.assertRaises(TclError, tcl.getdouble, 'a')
        self.assertRaises((TypeError, ValueError, TclError),
                          tcl.getdouble, '42.5\0')
        self.assertRaises((UnicodeEncodeError, ValueError, TclError),
                          tcl.getdouble, '42.5\ud800')

    def test_getboolean(self):
        tcl = self.interp.tk
        self.assertIs(tcl.getboolean('on'), True)
        self.assertIs(tcl.getboolean('1'), True)
        self.assertIs(tcl.getboolean(42), True)
        self.assertIs(tcl.getboolean(0), False)
        self.assertRaises(TypeError, tcl.getboolean)
        self.assertRaises(TypeError, tcl.getboolean, 'on', '1')
        self.assertRaises(TypeError, tcl.getboolean, b'on')
        self.assertRaises(TypeError, tcl.getboolean, 1.0)
        self.assertRaises(TclError, tcl.getboolean, 'a')
        self.assertRaises((TypeError, ValueError, TclError),
                          tcl.getboolean, 'on\0')
        self.assertRaises((UnicodeEncodeError, ValueError, TclError),
                          tcl.getboolean, 'on\ud800')

    def testEvalFile(self):
        tcl = self.interp
        with open(support.TESTFN, 'w') as f:
            self.addCleanup(support.unlink, support.TESTFN)
            f.write("""set a 1
            set b 2
            set c [ expr $a + $b ]
            """)
        tcl.evalfile(support.TESTFN)
        self.assertEqual(tcl.eval('set a'),'1')
        self.assertEqual(tcl.eval('set b'),'2')
        self.assertEqual(tcl.eval('set c'),'3')

    def test_evalfile_null_in_result(self):
        tcl = self.interp
        with open(support.TESTFN, 'w') as f:
            self.addCleanup(support.unlink, support.TESTFN)
            f.write("""
            set a "a\0b"
            set b "a\\0b"
            """)
        tcl.evalfile(support.TESTFN)
        self.assertEqual(tcl.eval('set a'), 'a\x00b')
        self.assertEqual(tcl.eval('set b'), 'a\x00b')

    def testEvalFileException(self):
        tcl = self.interp
        filename = "doesnotexists"
        try:
            os.remove(filename)
        except Exception as e:
            pass
        self.assertRaises(TclError,tcl.evalfile,filename)

    def testPackageRequireException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'package require DNE')

    @unittest.skipUnless(sys.platform == 'win32', 'Requires Windows')
    def testLoadWithUNC(self):
        # Build a UNC path from the regular path.
        # Something like
        #   \\%COMPUTERNAME%\c$\python27\python.exe

        fullname = os.path.abspath(sys.executable)
        if fullname[1] != ':':
            raise unittest.SkipTest('Absolute path should have drive part')
        unc_name = r'\\%s\%s$\%s' % (os.environ['COMPUTERNAME'],
                                    fullname[0],
                                    fullname[3:])
        if not os.path.exists(unc_name):
            raise unittest.SkipTest('Cannot connect to UNC Path')

        with support.EnvironmentVarGuard() as env:
            env.unset("TCL_LIBRARY")
            stdout = subprocess.check_output(
                    [unc_name, '-c', 'import tkinter; print(tkinter)'])

        self.assertIn(b'tkinter', stdout)

    def test_exprstring(self):
        tcl = self.interp
        tcl.call('set', 'a', 3)
        tcl.call('set', 'b', 6)
        def check(expr, expected):
            result = tcl.exprstring(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, str)

        self.assertRaises(TypeError, tcl.exprstring)
        self.assertRaises(TypeError, tcl.exprstring, '8.2', '+6')
        self.assertRaises(TypeError, tcl.exprstring, b'8.2 + 6')
        self.assertRaises(TclError, tcl.exprstring, 'spam')
        check('', '0')
        check('8.2 + 6', '14.2')
        check('3.1 + $a', '6.1')
        check('2 + "$a.$b"', '5.6')
        check('4*[llength "6 2"]', '8')
        check('{word one} < "word $a"', '0')
        check('4*2 < 7', '0')
        check('hypot($a, 4)', '5.0')
        check('5 / 4', '1')
        check('5 / 4.0', '1.25')
        check('5 / ( [string length "abcd"] + 0.0 )', '1.25')
        check('20.0/5.0', '4.0')
        check('"0x03" > "2"', '1')
        check('[string length "a\xbd\u20ac"]', '3')
        check(r'[string length "a\xbd\u20ac"]', '3')
        check('"abc"', 'abc')
        check('"a\xbd\u20ac"', 'a\xbd\u20ac')
        check(r'"a\xbd\u20ac"', 'a\xbd\u20ac')
        check(r'"a\0b"', 'a\x00b')
        if tcl_version >= (8, 5):  # bignum was added in Tcl 8.5
            check('2**64', str(2**64))

    def test_exprdouble(self):
        tcl = self.interp
        tcl.call('set', 'a', 3)
        tcl.call('set', 'b', 6)
        def check(expr, expected):
            result = tcl.exprdouble(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, float)

        self.assertRaises(TypeError, tcl.exprdouble)
        self.assertRaises(TypeError, tcl.exprdouble, '8.2', '+6')
        self.assertRaises(TypeError, tcl.exprdouble, b'8.2 + 6')
        self.assertRaises(TclError, tcl.exprdouble, 'spam')
        check('', 0.0)
        check('8.2 + 6', 14.2)
        check('3.1 + $a', 6.1)
        check('2 + "$a.$b"', 5.6)
        check('4*[llength "6 2"]', 8.0)
        check('{word one} < "word $a"', 0.0)
        check('4*2 < 7', 0.0)
        check('hypot($a, 4)', 5.0)
        check('5 / 4', 1.0)
        check('5 / 4.0', 1.25)
        check('5 / ( [string length "abcd"] + 0.0 )', 1.25)
        check('20.0/5.0', 4.0)
        check('"0x03" > "2"', 1.0)
        check('[string length "a\xbd\u20ac"]', 3.0)
        check(r'[string length "a\xbd\u20ac"]', 3.0)
        self.assertRaises(TclError, tcl.exprdouble, '"abc"')
        if tcl_version >= (8, 5):  # bignum was added in Tcl 8.5
            check('2**64', float(2**64))

    def test_exprlong(self):
        tcl = self.interp
        tcl.call('set', 'a', 3)
        tcl.call('set', 'b', 6)
        def check(expr, expected):
            result = tcl.exprlong(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, int)

        self.assertRaises(TypeError, tcl.exprlong)
        self.assertRaises(TypeError, tcl.exprlong, '8.2', '+6')
        self.assertRaises(TypeError, tcl.exprlong, b'8.2 + 6')
        self.assertRaises(TclError, tcl.exprlong, 'spam')
        check('', 0)
        check('8.2 + 6', 14)
        check('3.1 + $a', 6)
        check('2 + "$a.$b"', 5)
        check('4*[llength "6 2"]', 8)
        check('{word one} < "word $a"', 0)
        check('4*2 < 7', 0)
        check('hypot($a, 4)', 5)
        check('5 / 4', 1)
        check('5 / 4.0', 1)
        check('5 / ( [string length "abcd"] + 0.0 )', 1)
        check('20.0/5.0', 4)
        check('"0x03" > "2"', 1)
        check('[string length "a\xbd\u20ac"]', 3)
        check(r'[string length "a\xbd\u20ac"]', 3)
        self.assertRaises(TclError, tcl.exprlong, '"abc"')
        if tcl_version >= (8, 5):  # bignum was added in Tcl 8.5
            self.assertRaises(TclError, tcl.exprlong, '2**64')

    def test_exprboolean(self):
        tcl = self.interp
        tcl.call('set', 'a', 3)
        tcl.call('set', 'b', 6)
        def check(expr, expected):
            result = tcl.exprboolean(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, int)
            self.assertNotIsInstance(result, bool)

        self.assertRaises(TypeError, tcl.exprboolean)
        self.assertRaises(TypeError, tcl.exprboolean, '8.2', '+6')
        self.assertRaises(TypeError, tcl.exprboolean, b'8.2 + 6')
        self.assertRaises(TclError, tcl.exprboolean, 'spam')
        check('', False)
        for value in ('0', 'false', 'no', 'off'):
            check(value, False)
            check('"%s"' % value, False)
            check('{%s}' % value, False)
        for value in ('1', 'true', 'yes', 'on'):
            check(value, True)
            check('"%s"' % value, True)
            check('{%s}' % value, True)
        check('8.2 + 6', True)
        check('3.1 + $a', True)
        check('2 + "$a.$b"', True)
        check('4*[llength "6 2"]', True)
        check('{word one} < "word $a"', False)
        check('4*2 < 7', False)
        check('hypot($a, 4)', True)
        check('5 / 4', True)
        check('5 / 4.0', True)
        check('5 / ( [string length "abcd"] + 0.0 )', True)
        check('20.0/5.0', True)
        check('"0x03" > "2"', True)
        check('[string length "a\xbd\u20ac"]', True)
        check(r'[string length "a\xbd\u20ac"]', True)
        self.assertRaises(TclError, tcl.exprboolean, '"abc"')
        if tcl_version >= (8, 5):  # bignum was added in Tcl 8.5
            check('2**64', True)

    @unittest.skipUnless(tcl_version >= (8, 5), 'requires Tcl version >= 8.5')
    def test_booleans(self):
        tcl = self.interp
        def check(expr, expected):
            result = tcl.call('expr', expr)
            if tcl.wantobjects():
                self.assertEqual(result, expected)
                self.assertIsInstance(result, int)
            else:
                self.assertIn(result, (expr, str(int(expected))))
                self.assertIsInstance(result, str)
        check('true', True)
        check('yes', True)
        check('on', True)
        check('false', False)
        check('no', False)
        check('off', False)
        check('1 < 2', True)
        check('1 > 2', False)

    def test_expr_bignum(self):
        tcl = self.interp
        for i in self.get_integers():
            result = tcl.call('expr', str(i))
            if self.wantobjects:
                self.assertEqual(result, i)
                self.assertIsInstance(result, int)
            else:
                self.assertEqual(result, str(i))
                self.assertIsInstance(result, str)
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            self.assertRaises(TclError, tcl.call, 'expr', str(2**1000))

    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)

        self.assertEqual(passValue(True), True if self.wantobjects else '1')
        self.assertEqual(passValue(False), False if self.wantobjects else '0')
        self.assertEqual(passValue('string'), 'string')
        self.assertEqual(passValue('string\u20ac'), 'string\u20ac')
        self.assertEqual(passValue('str\x00ing'), 'str\x00ing')
        self.assertEqual(passValue('str\x00ing\xbd'), 'str\x00ing\xbd')
        self.assertEqual(passValue('str\x00ing\u20ac'), 'str\x00ing\u20ac')
        self.assertEqual(passValue(b'str\x00ing'),
                         b'str\x00ing' if self.wantobjects else 'str\x00ing')
        self.assertEqual(passValue(b'str\xc0\x80ing'),
                         b'str\xc0\x80ing' if self.wantobjects else 'str\xc0\x80ing')
        self.assertEqual(passValue(b'str\xbding'),
                         b'str\xbding' if self.wantobjects else 'str\xbding')
        for i in self.get_integers():
            self.assertEqual(passValue(i), i if self.wantobjects else str(i))
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            self.assertEqual(passValue(2**1000), str(2**1000))
        for f in (0.0, 1.0, -1.0, 1/3,
                  sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            if self.wantobjects:
                self.assertEqual(passValue(f), f)
            else:
                self.assertEqual(float(passValue(f)), f)
        if self.wantobjects:
            f = passValue(float('nan'))
            self.assertNotEqual(f, f)
            self.assertEqual(passValue(float('inf')), float('inf'))
            self.assertEqual(passValue(-float('inf')), -float('inf'))
        else:
            self.assertEqual(float(passValue(float('inf'))), float('inf'))
            self.assertEqual(float(passValue(-float('inf'))), -float('inf'))
            # XXX NaN representation can be not parsable by float()
        self.assertEqual(passValue((1, '2', (3.4,))),
                         (1, '2', (3.4,)) if self.wantobjects else '1 2 3.4')
        self.assertEqual(passValue(['a', ['b', 'c']]),
                         ('a', ('b', 'c')) if self.wantobjects else 'a {b c}')

    def test_user_command(self):
        result = None
        def testfunc(arg):
            nonlocal result
            result = arg
            return arg
        self.interp.createcommand('testfunc', testfunc)
        self.addCleanup(self.interp.tk.deletecommand, 'testfunc')
        def check(value, expected=None, *, eq=self.assertEqual):
            if expected is None:
                expected = value
            nonlocal result
            result = None
            r = self.interp.call('testfunc', value)
            self.assertIsInstance(result, str)
            eq(result, expected)
            self.assertIsInstance(r, str)
            eq(r, expected)
        def float_eq(actual, expected):
            self.assertAlmostEqual(float(actual), expected,
                                   delta=abs(expected) * 1e-10)

        check(True, '1')
        check(False, '0')
        check('string')
        check('string\xbd')
        check('string\u20ac')
        check('')
        check(b'string', 'string')
        check(b'string\xe2\x82\xac', 'string\xe2\x82\xac')
        check(b'string\xbd', 'string\xbd')
        check(b'', '')
        check('str\x00ing')
        check('str\x00ing\xbd')
        check('str\x00ing\u20ac')
        check(b'str\x00ing', 'str\x00ing')
        check(b'str\xc0\x80ing', 'str\xc0\x80ing')
        check(b'str\xc0\x80ing\xe2\x82\xac', 'str\xc0\x80ing\xe2\x82\xac')
        for i in self.get_integers():
            check(i, str(i))
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            check(2**1000, str(2**1000))
        for f in (0.0, 1.0, -1.0):
            check(f, repr(f))
        for f in (1/3.0, sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            check(f, eq=float_eq)
        check(float('inf'), eq=float_eq)
        check(-float('inf'), eq=float_eq)
        # XXX NaN representation can be not parsable by float()
        check((), '')
        check((1, (2,), (3, 4), '5 6', ()), '1 2 {3 4} {5 6} {}')
        check([1, [2,], [3, 4], '5 6', []], '1 2 {3 4} {5 6} {}')

    def test_splitlist(self):
        splitlist = self.interp.tk.splitlist
        call = self.interp.tk.call
        self.assertRaises(TypeError, splitlist)
        self.assertRaises(TypeError, splitlist, 'a', 'b')
        self.assertRaises(TypeError, splitlist, 2)
        testcases = [
            ('2', ('2',)),
            ('', ()),
            ('{}', ('',)),
            ('""', ('',)),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (b'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \u20ac', ('a', '\u20ac')),
            (b'a \xe2\x82\xac', ('a', '\u20ac')),
            (b'a\xc0\x80b c\xc0\x80d', ('a\x00b', 'c\x00d')),
            ('a {b c}', ('a', 'b c')),
            (r'a b\ c', ('a', 'b c')),
            (('a', 'b c'), ('a', 'b c')),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            ((), ()),
            ([], ()),
            (['a', ['b', 'c']], ('a', ['b', 'c'])),
            (call('list', 1, '2', (3.4,)),
                (1, '2', (3.4,)) if self.wantobjects else
                ('1', '2', '3.4')),
        ]
        tk_patchlevel = get_tk_patchlevel()
        if tcl_version >= (8, 5):
            if not self.wantobjects or tk_patchlevel < (8, 5, 5):
                # Before 8.5.5 dicts were converted to lists through string
                expected = ('12', '\u20ac', '\xe2\x82\xac', '3.4')
            else:
                expected = (12, '\u20ac', b'\xe2\x82\xac', (3.4,))
            testcases += [
                (call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac', (3.4,)),
                    expected),
            ]
        dbg_info = ('want objects? %s, Tcl version: %s, Tk patchlevel: %s'
                    % (self.wantobjects, tcl_version, tk_patchlevel))
        for arg, res in testcases:
            self.assertEqual(splitlist(arg), res,
                             'arg=%a, %s' % (arg, dbg_info))
        self.assertRaises(TclError, splitlist, '{')

    def test_split(self):
        split = self.interp.tk.split
        call = self.interp.tk.call
        self.assertRaises(TypeError, split)
        self.assertRaises(TypeError, split, 'a', 'b')
        self.assertRaises(TypeError, split, 2)
        testcases = [
            ('2', '2'),
            ('', ''),
            ('{}', ''),
            ('""', ''),
            ('{', '{'),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (b'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \u20ac', ('a', '\u20ac')),
            (b'a \xe2\x82\xac', ('a', '\u20ac')),
            (b'a\xc0\x80b', 'a\x00b'),
            (b'a\xc0\x80b c\xc0\x80d', ('a\x00b', 'c\x00d')),
            (b'{a\xc0\x80b c\xc0\x80d', '{a\x00b c\x00d'),
            ('a {b c}', ('a', ('b', 'c'))),
            (r'a b\ c', ('a', ('b', 'c'))),
            (('a', b'b c'), ('a', ('b', 'c'))),
            (('a', 'b c'), ('a', ('b', 'c'))),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            (('a', (2, 3.4)), ('a', (2, 3.4))),
            ((), ()),
            ([], ()),
            (['a', 'b c'], ('a', ('b', 'c'))),
            (['a', ['b', 'c']], ('a', ('b', 'c'))),
            (call('list', 1, '2', (3.4,)),
                (1, '2', (3.4,)) if self.wantobjects else
                ('1', '2', '3.4')),
        ]
        if tcl_version >= (8, 5):
            if not self.wantobjects or get_tk_patchlevel() < (8, 5, 5):
                # Before 8.5.5 dicts were converted to lists through string
                expected = ('12', '\u20ac', '\xe2\x82\xac', '3.4')
            else:
                expected = (12, '\u20ac', b'\xe2\x82\xac', (3.4,))
            testcases += [
                (call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac', (3.4,)),
                    expected),
            ]
        for arg, res in testcases:
            self.assertEqual(split(arg), res, msg=arg)

    def test_splitdict(self):
        splitdict = tkinter._splitdict
        tcl = self.interp.tk

        arg = '-a {1 2 3} -something foo status {}'
        self.assertEqual(splitdict(tcl, arg, False),
            {'-a': '1 2 3', '-something': 'foo', 'status': ''})
        self.assertEqual(splitdict(tcl, arg),
            {'a': '1 2 3', 'something': 'foo', 'status': ''})

        arg = ('-a', (1, 2, 3), '-something', 'foo', 'status', '{}')
        self.assertEqual(splitdict(tcl, arg, False),
            {'-a': (1, 2, 3), '-something': 'foo', 'status': '{}'})
        self.assertEqual(splitdict(tcl, arg),
            {'a': (1, 2, 3), 'something': 'foo', 'status': '{}'})

        self.assertRaises(RuntimeError, splitdict, tcl, '-a b -c ')
        self.assertRaises(RuntimeError, splitdict, tcl, ('-a', 'b', '-c'))

        arg = tcl.call('list',
                        '-a', (1, 2, 3), '-something', 'foo', 'status', ())
        self.assertEqual(splitdict(tcl, arg),
            {'a': (1, 2, 3) if self.wantobjects else '1 2 3',
             'something': 'foo', 'status': ''})

        if tcl_version >= (8, 5):
            arg = tcl.call('dict', 'create',
                           '-a', (1, 2, 3), '-something', 'foo', 'status', ())
            if not self.wantobjects or get_tk_patchlevel() < (8, 5, 5):
                # Before 8.5.5 dicts were converted to lists through string
                expected = {'a': '1 2 3', 'something': 'foo', 'status': ''}
            else:
                expected = {'a': (1, 2, 3), 'something': 'foo', 'status': ''}
            self.assertEqual(splitdict(tcl, arg), expected)
Exemplo n.º 39
0
 def setUp(self):
     self.interp = Tcl()
     self.wantobjects = self.interp.tk.wantobjects()
Exemplo n.º 40
0
 def setUp(self):
     self.interp = Tcl()
Exemplo n.º 41
0
class TclTest(unittest.TestCase):

    def setUp(self):
        self.interp = Tcl()
        self.wantobjects = self.interp.tk.wantobjects()

    def testEval(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.eval('set a'),'1')

    def testEvalException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'set a')

    def testEvalException2(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'this is wrong')

    def testCall(self):
        tcl = self.interp
        tcl.call('set','a','1')
        self.assertEqual(tcl.call('set','a'),'1')

    def testCallException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.call,'set','a')

    def testCallException2(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.call,'this','is','wrong')

    def testSetVar(self):
        tcl = self.interp
        tcl.setvar('a','1')
        self.assertEqual(tcl.eval('set a'),'1')

    def testSetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)','1')
        self.assertEqual(tcl.eval('set a(1)'),'1')

    def testGetVar(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.getvar('a'),'1')

    def testGetVarArray(self):
        tcl = self.interp
        tcl.eval('set a(1) 1')
        self.assertEqual(tcl.getvar('a(1)'),'1')

    def testGetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.getvar,'a')

    def testGetVarArrayException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.getvar,'a(1)')

    def testUnsetVar(self):
        tcl = self.interp
        tcl.setvar('a',1)
        self.assertEqual(tcl.eval('info exists a'),'1')
        tcl.unsetvar('a')
        self.assertEqual(tcl.eval('info exists a'),'0')

    def testUnsetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)',1)
        tcl.setvar('a(2)',2)
        self.assertEqual(tcl.eval('info exists a(1)'),'1')
        self.assertEqual(tcl.eval('info exists a(2)'),'1')
        tcl.unsetvar('a(1)')
        self.assertEqual(tcl.eval('info exists a(1)'),'0')
        self.assertEqual(tcl.eval('info exists a(2)'),'1')

    def testUnsetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.unsetvar,'a')

    def testEvalFile(self):
        tcl = self.interp
        filename = "testEvalFile.tcl"
        fd = open(filename,'w')
        script = """set a 1
        set b 2
        set c [ expr $a + $b ]
        """
        fd.write(script)
        fd.close()
        tcl.evalfile(filename)
        os.remove(filename)
        self.assertEqual(tcl.eval('set a'),'1')
        self.assertEqual(tcl.eval('set b'),'2')
        self.assertEqual(tcl.eval('set c'),'3')

    def testEvalFileException(self):
        tcl = self.interp
        filename = "doesnotexists"
        try:
            os.remove(filename)
        except Exception as e:
            pass
        self.assertRaises(TclError,tcl.evalfile,filename)

    def testPackageRequireException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'package require DNE')

    @unittest.skipUnless(sys.platform == 'win32', 'Requires Windows')
    def testLoadWithUNC(self):
        # Build a UNC path from the regular path.
        # Something like
        #   \\%COMPUTERNAME%\c$\python27\python.exe

        fullname = os.path.abspath(sys.executable)
        if fullname[1] != ':':
            raise unittest.SkipTest('Absolute path should have drive part')
        unc_name = r'\\%s\%s$\%s' % (os.environ['COMPUTERNAME'],
                                    fullname[0],
                                    fullname[3:])
        if not os.path.exists(unc_name):
            raise unittest.SkipTest('Cannot connect to UNC Path')

        with support.EnvironmentVarGuard() as env:
            env.unset("TCL_LIBRARY")
            f = os.popen('%s -c "import tkinter; print(tkinter)"' % (unc_name,))

        self.assertIn('tkinter', f.read())
        # exit code must be zero
        self.assertEqual(f.close(), None)

    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)

        self.assertEqual(passValue(True), True if self.wantobjects else '1')
        self.assertEqual(passValue(False), False if self.wantobjects else '0')
        self.assertEqual(passValue('string'), 'string')
        self.assertEqual(passValue('string\u20ac'), 'string\u20ac')
        for i in (0, 1, -1, 2**31-1, -2**31):
            self.assertEqual(passValue(i), i if self.wantobjects else str(i))
        for f in (0.0, 1.0, -1.0, 1/3,
                  sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            if self.wantobjects:
                self.assertEqual(passValue(f), f)
            else:
                self.assertEqual(float(passValue(f)), f)
        if self.wantobjects:
            f = passValue(float('nan'))
            self.assertNotEqual(f, f)
            self.assertEqual(passValue(float('inf')), float('inf'))
            self.assertEqual(passValue(-float('inf')), -float('inf'))
        else:
            f = float(passValue(float('nan')))
            self.assertNotEqual(f, f)
            self.assertEqual(float(passValue(float('inf'))), float('inf'))
            self.assertEqual(float(passValue(-float('inf'))), -float('inf'))
        self.assertEqual(passValue((1, '2', (3.4,))),
                         (1, '2', (3.4,)) if self.wantobjects else '1 2 3.4')

    def test_user_command(self):
        result = None
        def testfunc(arg):
            nonlocal result
            result = arg
            return arg
        self.interp.createcommand('testfunc', testfunc)
        def check(value, expected, eq=self.assertEqual):
            r = self.interp.call('testfunc', value)
            self.assertIsInstance(result, str)
            eq(result, expected)
            self.assertIsInstance(r, str)
            eq(r, expected)
        def float_eq(actual, expected):
            expected = float(expected)
            self.assertAlmostEqual(float(actual), expected,
                                   delta=abs(expected) * 1e-10)
        def nan_eq(actual, expected):
            actual = float(actual)
            self.assertNotEqual(actual, actual)

        check(True, '1')
        check(False, '0')
        check('string', 'string')
        check('string\xbd', 'string\xbd')
        check('string\u20ac', 'string\u20ac')
        for i in (0, 1, -1, 2**31-1, -2**31):
            check(i, str(i))
        for f in (0.0, 1.0, -1.0):
            check(f, repr(f))
        for f in (1/3.0, sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            check(f, f, eq=float_eq)
        check(float('inf'), 'Inf', eq=float_eq)
        check(-float('inf'), '-Inf', eq=float_eq)
        check(float('nan'), 'NaN', eq=nan_eq)
        check((), '')
        check((1, (2,), (3, 4), '5 6', ()), '1 2 {3 4} {5 6} {}')

    def test_splitlist(self):
        splitlist = self.interp.tk.splitlist
        call = self.interp.tk.call
        self.assertRaises(TypeError, splitlist)
        self.assertRaises(TypeError, splitlist, 'a', 'b')
        self.assertRaises(TypeError, splitlist, 2)
        testcases = [
            ('2', ('2',)),
            ('', ()),
            ('{}', ('',)),
            ('""', ('',)),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (b'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \u20ac', ('a', '\u20ac')),
            (b'a \xe2\x82\xac', ('a', '\u20ac')),
            ('a {b c}', ('a', 'b c')),
            (r'a b\ c', ('a', 'b c')),
            (('a', 'b c'), ('a', 'b c')),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            ((), ()),
            (call('list', 1, '2', (3.4,)),
                (1, '2', (3.4,)) if self.wantobjects else
                ('1', '2', '3.4')),
        ]
        if tcl_version >= (8, 5):
            testcases += [
                (call('dict', 'create', 1, '\u20ac', b'\xe2\x82\xac', (3.4,)),
                    (1, '\u20ac', '\u20ac', (3.4,)) if self.wantobjects else
                    ('1', '\u20ac', '\u20ac', '3.4')),
            ]
        for arg, res in testcases:
            self.assertEqual(splitlist(arg), res, msg=arg)
        self.assertRaises(TclError, splitlist, '{')

    def test_split(self):
        split = self.interp.tk.split
        call = self.interp.tk.call
        self.assertRaises(TypeError, split)
        self.assertRaises(TypeError, split, 'a', 'b')
        self.assertRaises(TypeError, split, 2)
        testcases = [
            ('2', '2'),
            ('', ''),
            ('{}', ''),
            ('""', ''),
            ('{', '{'),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (b'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \u20ac', ('a', '\u20ac')),
            (b'a \xe2\x82\xac', ('a', '\u20ac')),
            ('a {b c}', ('a', ('b', 'c'))),
            (r'a b\ c', ('a', ('b', 'c'))),
            (('a', b'b c'), ('a', ('b', 'c'))),
            (('a', 'b c'), ('a', ('b', 'c'))),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            (('a', (2, 3.4)), ('a', (2, 3.4))),
            ((), ()),
            (call('list', 1, '2', (3.4,)),
                (1, '2', (3.4,)) if self.wantobjects else
                ('1', '2', '3.4')),
        ]
        if tcl_version >= (8, 5):
            testcases += [
                (call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac', (3.4,)),
                    (12, '\u20ac', '\u20ac', (3.4,)) if self.wantobjects else
                    ('12', '\u20ac', '\u20ac', '3.4')),
            ]
        for arg, res in testcases:
            self.assertEqual(split(arg), res, msg=arg)

    def test_merge(self):
        with support.check_warnings(('merge is deprecated',
                                     DeprecationWarning)):
            merge = self.interp.tk.merge
            call = self.interp.tk.call
            testcases = [
                ((), ''),
                (('a',), 'a'),
                ((2,), '2'),
                (('',), '{}'),
                ('{', '\\{'),
                (('a', 'b', 'c'), 'a b c'),
                ((' ', '\t', '\r', '\n'), '{ } {\t} {\r} {\n}'),
                (('a', ' ', 'c'), 'a { } c'),
                (('a', '€'), 'a €'),
                (('a', '\U000104a2'), 'a \U000104a2'),
                (('a', b'\xe2\x82\xac'), 'a €'),
                (('a', ('b', 'c')), 'a {b c}'),
                (('a', 2), 'a 2'),
                (('a', 3.4), 'a 3.4'),
                (('a', (2, 3.4)), 'a {2 3.4}'),
                ((), ''),
                ((call('list', 1, '2', (3.4,)),), '{1 2 3.4}'),
            ]
            if tcl_version >= (8, 5):
                testcases += [
                    ((call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac', (3.4,)),),
                     '{12 € € 3.4}'),
                ]
            for args, res in testcases:
                self.assertEqual(merge(*args), res, msg=args)
            self.assertRaises(UnicodeDecodeError, merge, b'\x80')
            self.assertRaises(UnicodeEncodeError, merge, '\udc80')
Exemplo n.º 42
0
 def setUp(self):
     self.interp = Tcl()
Exemplo n.º 43
0
class TclTest(unittest.TestCase):
    def setUp(self):
        self.interp = Tcl()

    def testEval(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.eval('set a'), '1')

    def testEvalException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.eval, 'set a')

    def testEvalException2(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.eval, 'this is wrong')

    def testCall(self):
        tcl = self.interp
        tcl.call('set', 'a', '1')
        self.assertEqual(tcl.call('set', 'a'), '1')

    def testCallException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.call, 'set', 'a')

    def testCallException2(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.call, 'this', 'is', 'wrong')

    def testSetVar(self):
        tcl = self.interp
        tcl.setvar('a', '1')
        self.assertEqual(tcl.eval('set a'), '1')

    def testSetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)', '1')
        self.assertEqual(tcl.eval('set a(1)'), '1')

    def testGetVar(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.getvar('a'), '1')

    def testGetVarArray(self):
        tcl = self.interp
        tcl.eval('set a(1) 1')
        self.assertEqual(tcl.getvar('a(1)'), '1')

    def testGetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.getvar, 'a')

    def testGetVarArrayException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.getvar, 'a(1)')

    def testUnsetVar(self):
        tcl = self.interp
        tcl.setvar('a', 1)
        self.assertEqual(tcl.eval('info exists a'), '1')
        tcl.unsetvar('a')
        self.assertEqual(tcl.eval('info exists a'), '0')

    def testUnsetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)', 1)
        tcl.setvar('a(2)', 2)
        self.assertEqual(tcl.eval('info exists a(1)'), '1')
        self.assertEqual(tcl.eval('info exists a(2)'), '1')
        tcl.unsetvar('a(1)')
        self.assertEqual(tcl.eval('info exists a(1)'), '0')
        self.assertEqual(tcl.eval('info exists a(2)'), '1')

    def testUnsetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.unsetvar, 'a')

    def testEvalFile(self):
        tcl = self.interp
        filename = "testEvalFile.tcl"
        fd = open(filename, 'w')
        script = """set a 1
        set b 2
        set c [ expr $a + $b ]
        """
        fd.write(script)
        fd.close()
        tcl.evalfile(filename)
        os.remove(filename)
        self.assertEqual(tcl.eval('set a'), '1')
        self.assertEqual(tcl.eval('set b'), '2')
        self.assertEqual(tcl.eval('set c'), '3')

    def testEvalFileException(self):
        tcl = self.interp
        filename = "doesnotexists"
        try:
            os.remove(filename)
        except Exception as e:
            pass
        self.assertRaises(TclError, tcl.evalfile, filename)

    def testPackageRequireException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.eval, 'package require DNE')

    @unittest.skipUnless(sys.platform == 'win32', 'Requires Windows')
    def testLoadWithUNC(self):
        # Build a UNC path from the regular path.
        # Something like
        #   \\%COMPUTERNAME%\c$\python27\python.exe

        fullname = os.path.abspath(sys.executable)
        if fullname[1] != ':':
            raise unittest.SkipTest('Absolute path should have drive part')
        unc_name = r'\\%s\%s$\%s' % (os.environ['COMPUTERNAME'], fullname[0],
                                     fullname[3:])
        if not os.path.exists(unc_name):
            raise unittest.SkipTest('Cannot connect to UNC Path')

        with support.EnvironmentVarGuard() as env:
            env.unset("TCL_LIBRARY")
            f = os.popen('%s -c "import tkinter; print(tkinter)"' %
                         (unc_name, ))

        self.assertIn('tkinter', f.read())
        # exit code must be zero
        self.assertEqual(f.close(), None)

    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)

        self.assertEqual(passValue(True), True)
        self.assertEqual(passValue(False), False)
        self.assertEqual(passValue('string'), 'string')
        self.assertEqual(passValue('string\u20ac'), 'string\u20ac')
        for i in (0, 1, -1, 2**31 - 1, -2**31):
            self.assertEqual(passValue(i), i)
        for f in (0.0, 1.0, -1.0, 1 / 3, sys.float_info.min,
                  sys.float_info.max, -sys.float_info.min,
                  -sys.float_info.max):
            self.assertEqual(passValue(f), f)
        for f in float('nan'), float('inf'), -float('inf'):
            if f != f:  # NaN
                self.assertNotEqual(passValue(f), f)
            else:
                self.assertEqual(passValue(f), f)
        self.assertEqual(passValue((1, '2', (3.4, ))), (1, '2', (3.4, )))

    def test_splitlist(self):
        splitlist = self.interp.tk.splitlist
        call = self.interp.tk.call
        self.assertRaises(TypeError, splitlist)
        self.assertRaises(TypeError, splitlist, 'a', 'b')
        self.assertRaises(TypeError, splitlist, 2)
        testcases = [
            ('2', ('2', )),
            ('', ()),
            ('{}', ('', )),
            ('""', ('', )),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (b'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \u20ac', ('a', '\u20ac')),
            (b'a \xe2\x82\xac', ('a', '\u20ac')),
            ('a {b c}', ('a', 'b c')),
            (r'a b\ c', ('a', 'b c')),
            (('a', 'b c'), ('a', 'b c')),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            ((), ()),
            (call('list', 1, '2', (3.4, )), (1, '2', (3.4, ))),
        ]
        if tcl_version >= (8, 5):
            testcases += [
                (call('dict', 'create', 1, '\u20ac', b'\xe2\x82\xac',
                      (3.4, )), (1, '\u20ac', '\u20ac', (3.4, ))),
            ]
        for arg, res in testcases:
            self.assertEqual(splitlist(arg), res, msg=arg)
        self.assertRaises(TclError, splitlist, '{')

    def test_split(self):
        split = self.interp.tk.split
        call = self.interp.tk.call
        self.assertRaises(TypeError, split)
        self.assertRaises(TypeError, split, 'a', 'b')
        self.assertRaises(TypeError, split, 2)
        testcases = [
            ('2', '2'),
            ('', ''),
            ('{}', ''),
            ('""', ''),
            ('{', '{'),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (b'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \u20ac', ('a', '\u20ac')),
            (b'a \xe2\x82\xac', ('a', '\u20ac')),
            ('a {b c}', ('a', ('b', 'c'))),
            (r'a b\ c', ('a', ('b', 'c'))),
            (('a', b'b c'), ('a', ('b', 'c'))),
            (('a', 'b c'), ('a', ('b', 'c'))),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            (('a', (2, 3.4)), ('a', (2, 3.4))),
            ((), ()),
            (call('list', 1, '2', (3.4, )), (1, '2', (3.4, ))),
        ]
        if tcl_version >= (8, 5):
            testcases += [
                (call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac',
                      (3.4, )), (12, '\u20ac', '\u20ac', (3.4, ))),
            ]
        for arg, res in testcases:
            self.assertEqual(split(arg), res, msg=arg)
Exemplo n.º 44
0
class TclTest(unittest.TestCase):
    def setUp(self):
        self.interp = Tcl()
        self.wantobjects = self.interp.tk.wantobjects()

    def testEval(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.eval('set a'), '1')

    def test_eval_null_in_result(self):
        tcl = self.interp
        self.assertEqual(tcl.eval('set a "a\\0b"'), 'a\x00b')

    def testEvalException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.eval, 'set a')

    def testEvalException2(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.eval, 'this is wrong')

    def testCall(self):
        tcl = self.interp
        tcl.call('set', 'a', '1')
        self.assertEqual(tcl.call('set', 'a'), '1')

    def testCallException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.call, 'set', 'a')

    def testCallException2(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.call, 'this', 'is', 'wrong')

    def testSetVar(self):
        tcl = self.interp
        tcl.setvar('a', '1')
        self.assertEqual(tcl.eval('set a'), '1')

    def testSetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)', '1')
        self.assertEqual(tcl.eval('set a(1)'), '1')

    def testGetVar(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.getvar('a'), '1')

    def testGetVarArray(self):
        tcl = self.interp
        tcl.eval('set a(1) 1')
        self.assertEqual(tcl.getvar('a(1)'), '1')

    def testGetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.getvar, 'a')

    def testGetVarArrayException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.getvar, 'a(1)')

    def testUnsetVar(self):
        tcl = self.interp
        tcl.setvar('a', 1)
        self.assertEqual(tcl.eval('info exists a'), '1')
        tcl.unsetvar('a')
        self.assertEqual(tcl.eval('info exists a'), '0')

    def testUnsetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)', 1)
        tcl.setvar('a(2)', 2)
        self.assertEqual(tcl.eval('info exists a(1)'), '1')
        self.assertEqual(tcl.eval('info exists a(2)'), '1')
        tcl.unsetvar('a(1)')
        self.assertEqual(tcl.eval('info exists a(1)'), '0')
        self.assertEqual(tcl.eval('info exists a(2)'), '1')

    def testUnsetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.unsetvar, 'a')

    def testEvalFile(self):
        tcl = self.interp
        with open(support.TESTFN, 'w') as f:
            self.addCleanup(support.unlink, support.TESTFN)
            f.write("""set a 1
            set b 2
            set c [ expr $a + $b ]
            """)
        tcl.evalfile(support.TESTFN)
        self.assertEqual(tcl.eval('set a'), '1')
        self.assertEqual(tcl.eval('set b'), '2')
        self.assertEqual(tcl.eval('set c'), '3')

    def test_evalfile_null_in_result(self):
        tcl = self.interp
        with open(support.TESTFN, 'w') as f:
            self.addCleanup(support.unlink, support.TESTFN)
            f.write("""
            set a "a\0b"
            set b "a\\0b"
            """)
        tcl.evalfile(support.TESTFN)
        self.assertEqual(tcl.eval('set a'), 'a\x00b')
        self.assertEqual(tcl.eval('set b'), 'a\x00b')

    def testEvalFileException(self):
        tcl = self.interp
        filename = "doesnotexists"
        try:
            os.remove(filename)
        except Exception as e:
            pass
        self.assertRaises(TclError, tcl.evalfile, filename)

    def testPackageRequireException(self):
        tcl = self.interp
        self.assertRaises(TclError, tcl.eval, 'package require DNE')

    @unittest.skipUnless(sys.platform == 'win32', 'Requires Windows')
    def testLoadWithUNC(self):
        # Build a UNC path from the regular path.
        # Something like
        #   \\%COMPUTERNAME%\c$\python27\python.exe

        fullname = os.path.abspath(sys.executable)
        if fullname[1] != ':':
            raise unittest.SkipTest('Absolute path should have drive part')
        unc_name = r'\\%s\%s$\%s' % (os.environ['COMPUTERNAME'], fullname[0],
                                     fullname[3:])
        if not os.path.exists(unc_name):
            raise unittest.SkipTest('Cannot connect to UNC Path')

        with support.EnvironmentVarGuard() as env:
            env.unset("TCL_LIBRARY")
            f = os.popen('%s -c "import tkinter; print(tkinter)"' %
                         (unc_name, ))

        self.assertIn('tkinter', f.read())
        # exit code must be zero
        self.assertEqual(f.close(), None)

    def test_exprstring(self):
        tcl = self.interp
        tcl.call('set', 'a', 3)
        tcl.call('set', 'b', 6)

        def check(expr, expected):
            result = tcl.exprstring(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, str)

        self.assertRaises(TypeError, tcl.exprstring)
        self.assertRaises(TypeError, tcl.exprstring, '8.2', '+6')
        self.assertRaises(TypeError, tcl.exprstring, b'8.2 + 6')
        self.assertRaises(TclError, tcl.exprstring, 'spam')
        check('', '0')
        check('8.2 + 6', '14.2')
        check('3.1 + $a', '6.1')
        check('2 + "$a.$b"', '5.6')
        check('4*[llength "6 2"]', '8')
        check('{word one} < "word $a"', '0')
        check('4*2 < 7', '0')
        check('hypot($a, 4)', '5.0')
        check('5 / 4', '1')
        check('5 / 4.0', '1.25')
        check('5 / ( [string length "abcd"] + 0.0 )', '1.25')
        check('20.0/5.0', '4.0')
        check('"0x03" > "2"', '1')
        check('[string length "a\xbd\u20ac"]', '3')
        check(r'[string length "a\xbd\u20ac"]', '3')
        check('"abc"', 'abc')
        check('"a\xbd\u20ac"', 'a\xbd\u20ac')
        check(r'"a\xbd\u20ac"', 'a\xbd\u20ac')
        check(r'"a\0b"', 'a\x00b')
        if tcl_version >= (8, 5):
            check('2**64', str(2**64))

    def test_exprdouble(self):
        tcl = self.interp
        tcl.call('set', 'a', 3)
        tcl.call('set', 'b', 6)

        def check(expr, expected):
            result = tcl.exprdouble(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, float)

        self.assertRaises(TypeError, tcl.exprdouble)
        self.assertRaises(TypeError, tcl.exprdouble, '8.2', '+6')
        self.assertRaises(TypeError, tcl.exprdouble, b'8.2 + 6')
        self.assertRaises(TclError, tcl.exprdouble, 'spam')
        check('', 0.0)
        check('8.2 + 6', 14.2)
        check('3.1 + $a', 6.1)
        check('2 + "$a.$b"', 5.6)
        check('4*[llength "6 2"]', 8.0)
        check('{word one} < "word $a"', 0.0)
        check('4*2 < 7', 0.0)
        check('hypot($a, 4)', 5.0)
        check('5 / 4', 1.0)
        check('5 / 4.0', 1.25)
        check('5 / ( [string length "abcd"] + 0.0 )', 1.25)
        check('20.0/5.0', 4.0)
        check('"0x03" > "2"', 1.0)
        check('[string length "a\xbd\u20ac"]', 3.0)
        check(r'[string length "a\xbd\u20ac"]', 3.0)
        self.assertRaises(TclError, tcl.exprdouble, '"abc"')
        if tcl_version >= (8, 5):
            check('2**64', float(2**64))

    def test_exprlong(self):
        tcl = self.interp
        tcl.call('set', 'a', 3)
        tcl.call('set', 'b', 6)

        def check(expr, expected):
            result = tcl.exprlong(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, int)

        self.assertRaises(TypeError, tcl.exprlong)
        self.assertRaises(TypeError, tcl.exprlong, '8.2', '+6')
        self.assertRaises(TypeError, tcl.exprlong, b'8.2 + 6')
        self.assertRaises(TclError, tcl.exprlong, 'spam')
        check('', 0)
        check('8.2 + 6', 14)
        check('3.1 + $a', 6)
        check('2 + "$a.$b"', 5)
        check('4*[llength "6 2"]', 8)
        check('{word one} < "word $a"', 0)
        check('4*2 < 7', 0)
        check('hypot($a, 4)', 5)
        check('5 / 4', 1)
        check('5 / 4.0', 1)
        check('5 / ( [string length "abcd"] + 0.0 )', 1)
        check('20.0/5.0', 4)
        check('"0x03" > "2"', 1)
        check('[string length "a\xbd\u20ac"]', 3)
        check(r'[string length "a\xbd\u20ac"]', 3)
        self.assertRaises(TclError, tcl.exprlong, '"abc"')
        if tcl_version >= (8, 5):
            self.assertRaises(TclError, tcl.exprlong, '2**64')

    def test_exprboolean(self):
        tcl = self.interp
        tcl.call('set', 'a', 3)
        tcl.call('set', 'b', 6)

        def check(expr, expected):
            result = tcl.exprboolean(expr)
            self.assertEqual(result, expected)
            self.assertIsInstance(result, int)
            self.assertNotIsInstance(result, bool)

        self.assertRaises(TypeError, tcl.exprboolean)
        self.assertRaises(TypeError, tcl.exprboolean, '8.2', '+6')
        self.assertRaises(TypeError, tcl.exprboolean, b'8.2 + 6')
        self.assertRaises(TclError, tcl.exprboolean, 'spam')
        check('', False)
        for value in ('0', 'false', 'no', 'off'):
            check(value, False)
            check('"%s"' % value, False)
            check('{%s}' % value, False)
        for value in ('1', 'true', 'yes', 'on'):
            check(value, True)
            check('"%s"' % value, True)
            check('{%s}' % value, True)
        check('8.2 + 6', True)
        check('3.1 + $a', True)
        check('2 + "$a.$b"', True)
        check('4*[llength "6 2"]', True)
        check('{word one} < "word $a"', False)
        check('4*2 < 7', False)
        check('hypot($a, 4)', True)
        check('5 / 4', True)
        check('5 / 4.0', True)
        check('5 / ( [string length "abcd"] + 0.0 )', True)
        check('20.0/5.0', True)
        check('"0x03" > "2"', True)
        check('[string length "a\xbd\u20ac"]', True)
        check(r'[string length "a\xbd\u20ac"]', True)
        self.assertRaises(TclError, tcl.exprboolean, '"abc"')
        if tcl_version >= (8, 5):
            check('2**64', True)

    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)

        self.assertEqual(passValue(True), True if self.wantobjects else '1')
        self.assertEqual(passValue(False), False if self.wantobjects else '0')
        self.assertEqual(passValue('string'), 'string')
        self.assertEqual(passValue('string\u20ac'), 'string\u20ac')
        self.assertEqual(passValue('str\x00ing'), 'str\x00ing')
        self.assertEqual(passValue('str\x00ing\xbd'), 'str\x00ing\xbd')
        self.assertEqual(passValue('str\x00ing\u20ac'), 'str\x00ing\u20ac')
        self.assertEqual(passValue(b'str\x00ing'), 'str\x00ing')
        self.assertEqual(passValue(b'str\xc0\x80ing'), 'str\x00ing')
        for i in (0, 1, -1, 2**31 - 1, -2**31):
            self.assertEqual(passValue(i), i if self.wantobjects else str(i))
        for f in (0.0, 1.0, -1.0, 1 / 3, sys.float_info.min,
                  sys.float_info.max, -sys.float_info.min,
                  -sys.float_info.max):
            if self.wantobjects:
                self.assertEqual(passValue(f), f)
            else:
                self.assertEqual(float(passValue(f)), f)
        if self.wantobjects:
            f = passValue(float('nan'))
            self.assertNotEqual(f, f)
            self.assertEqual(passValue(float('inf')), float('inf'))
            self.assertEqual(passValue(-float('inf')), -float('inf'))
        else:
            f = float(passValue(float('nan')))
            self.assertNotEqual(f, f)
            self.assertEqual(float(passValue(float('inf'))), float('inf'))
            self.assertEqual(float(passValue(-float('inf'))), -float('inf'))
        self.assertEqual(passValue((1, '2', (3.4, ))),
                         (1, '2', (3.4, )) if self.wantobjects else '1 2 3.4')

    def test_user_command(self):
        result = None

        def testfunc(arg):
            nonlocal result
            result = arg
            return arg

        self.interp.createcommand('testfunc', testfunc)

        def check(value, expected, eq=self.assertEqual):
            r = self.interp.call('testfunc', value)
            self.assertIsInstance(result, str)
            eq(result, expected)
            self.assertIsInstance(r, str)
            eq(r, expected)

        def float_eq(actual, expected):
            expected = float(expected)
            self.assertAlmostEqual(float(actual),
                                   expected,
                                   delta=abs(expected) * 1e-10)

        def nan_eq(actual, expected):
            actual = float(actual)
            self.assertNotEqual(actual, actual)

        check(True, '1')
        check(False, '0')
        check('string', 'string')
        check('string\xbd', 'string\xbd')
        check('string\u20ac', 'string\u20ac')
        check(b'string', 'string')
        check(b'string\xe2\x82\xac', 'string\u20ac')
        check('str\x00ing', 'str\x00ing')
        check('str\x00ing\xbd', 'str\x00ing\xbd')
        check('str\x00ing\u20ac', 'str\x00ing\u20ac')
        check(b'str\xc0\x80ing', 'str\x00ing')
        check(b'str\xc0\x80ing\xe2\x82\xac', 'str\x00ing\u20ac')
        for i in (0, 1, -1, 2**31 - 1, -2**31):
            check(i, str(i))
        for f in (0.0, 1.0, -1.0):
            check(f, repr(f))
        for f in (1 / 3.0, sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            check(f, f, eq=float_eq)
        check(float('inf'), 'Inf', eq=float_eq)
        check(-float('inf'), '-Inf', eq=float_eq)
        check(float('nan'), 'NaN', eq=nan_eq)
        check((), '')
        check((1, (2, ), (3, 4), '5 6', ()), '1 2 {3 4} {5 6} {}')

    def test_splitlist(self):
        splitlist = self.interp.tk.splitlist
        call = self.interp.tk.call
        self.assertRaises(TypeError, splitlist)
        self.assertRaises(TypeError, splitlist, 'a', 'b')
        self.assertRaises(TypeError, splitlist, 2)
        testcases = [
            ('2', ('2', )),
            ('', ()),
            ('{}', ('', )),
            ('""', ('', )),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (b'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \u20ac', ('a', '\u20ac')),
            (b'a \xe2\x82\xac', ('a', '\u20ac')),
            (b'a\xc0\x80b c\xc0\x80d', ('a\x00b', 'c\x00d')),
            ('a {b c}', ('a', 'b c')),
            (r'a b\ c', ('a', 'b c')),
            (('a', 'b c'), ('a', 'b c')),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            ((), ()),
            (call('list', 1, '2',
                  (3.4, )), (1, '2', (3.4, )) if self.wantobjects else
             ('1', '2', '3.4')),
        ]
        if tcl_version >= (8, 5):
            if not self.wantobjects or get_tk_patchlevel() < (8, 5, 5):
                # Before 8.5.5 dicts were converted to lists through string
                expected = ('12', '\u20ac', '\u20ac', '3.4')
            else:
                expected = (12, '\u20ac', '\u20ac', (3.4, ))
            testcases += [
                (call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac',
                      (3.4, )), expected),
            ]
        for arg, res in testcases:
            self.assertEqual(splitlist(arg), res, msg=arg)
        self.assertRaises(TclError, splitlist, '{')

    def test_split(self):
        split = self.interp.tk.split
        call = self.interp.tk.call
        self.assertRaises(TypeError, split)
        self.assertRaises(TypeError, split, 'a', 'b')
        self.assertRaises(TypeError, split, 2)
        testcases = [
            ('2', '2'),
            ('', ''),
            ('{}', ''),
            ('""', ''),
            ('{', '{'),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (b'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \u20ac', ('a', '\u20ac')),
            (b'a \xe2\x82\xac', ('a', '\u20ac')),
            (b'a\xc0\x80b', 'a\x00b'),
            (b'a\xc0\x80b c\xc0\x80d', ('a\x00b', 'c\x00d')),
            (b'{a\xc0\x80b c\xc0\x80d', '{a\x00b c\x00d'),
            ('a {b c}', ('a', ('b', 'c'))),
            (r'a b\ c', ('a', ('b', 'c'))),
            (('a', b'b c'), ('a', ('b', 'c'))),
            (('a', 'b c'), ('a', ('b', 'c'))),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            (('a', (2, 3.4)), ('a', (2, 3.4))),
            ((), ()),
            (call('list', 1, '2',
                  (3.4, )), (1, '2', (3.4, )) if self.wantobjects else
             ('1', '2', '3.4')),
        ]
        if tcl_version >= (8, 5):
            if not self.wantobjects or get_tk_patchlevel() < (8, 5, 5):
                # Before 8.5.5 dicts were converted to lists through string
                expected = ('12', '\u20ac', '\u20ac', '3.4')
            else:
                expected = (12, '\u20ac', '\u20ac', (3.4, ))
            testcases += [
                (call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac',
                      (3.4, )), expected),
            ]
        for arg, res in testcases:
            self.assertEqual(split(arg), res, msg=arg)
Exemplo n.º 45
0
                    default='DeepGlint',
                    type=str,
                    help='save name')
parser.add_argument('-r',
                    '--ratio',
                    default=0.2,
                    type=float,
                    help='How many images do you want to use in validation')
parser.add_argument('-s', '--set', default=['train', 'val'])
args = parser.parse_args()

root = os.path.join('/home/ubuntu/data/', args.project)
# root = os.path.join('datasets', args.project)

ids = os.listdir(root)
ids = Tcl().call('lsort', '-dict', ids)
print('Total_ids :', len(ids))

min_n = 0
max_n = 0
cn = 0
for id in ids:
    images = os.listdir(os.path.join(root, id))

    if min_n == 0:
        min_n = len(images)
    max_n = max([max_n, len(images)])
    min_n = min([min_n, len(images)])

    if len(images) < 11:
        # print('id :', id)
 def testLoadTk(self):
     tcl = Tcl()
     self.assertRaises(TclError,tcl.winfo_geometry)
     tcl.loadtk()
     self.assertEqual('1x1+0+0', tcl.winfo_geometry())
     tcl.destroy()