Exemplo n.º 1
0
    def test_05_03_http_image_zipfile(self):
        # Make a zipfile using files accessed from the web
        def alter_fn(module):
            self.assertTrue(isinstance(module, C.CreateWebPage))
            module.wants_zip_file.value = True
            module.zipfile_name.value = ZIPFILE_NAME
            module.directory_choice.dir_choice = C.ABSOLUTE_FOLDER_NAME
            module.directory_choice.custom_path = cpprefs.get_default_image_directory()

        url_root = "http://cellprofiler.org/svnmirror/ExampleImages/ExampleSBSImages/"
        url_query = "?r=11710"
        filenames = [(url_root, fn + url_query) for fn in
                     ("Channel1-01-A-01.tif", "Channel2-01-A-01.tif",
                      "Channel1-02-A-02.tif", "Channel2-02-A-02.tif")]
        #
        # Make sure URLs are accessible
        #
        try:
            for filename in filenames:
                URLopener().open("".join(filename)).close()
        except IOError, e:
            def bad_url(e=e):
                raise e

            unittest.expectedFailure(bad_url)()
Exemplo n.º 2
0
 def test_MaximumRecursionDepthExceededWithComplexSecurity(self):
   skin = self.portal.portal_skins.custom
   colour = self.portal.portal_categories.colour
   colour.hasObject('green') or colour.newContent('green')
   login = str(time.time())
   script_id = ["ERP5Type_getSecurityCategoryMapping",
                "ERP5Type_getSecurityCategory"]
   createZODBPythonScript(skin, script_id[0], "",
     "return ((%r, ('colour',)),)" % script_id[1])
   createZODBPythonScript(skin, script_id[1],
     "base_category_list, user_name, object, portal_type, depth=[]", """if 1:
     # This should not be called recursively, or at least if should not fail.
     # Because RuntimeError is catched by 'except:' clauses, we detect it
     # with a static variable.
     depth.append(None)
     assert not portal_type, portal_type
     # the following line calls Base_zSearchRelatedObjectsByCategoryList
     object.getSourceDecisionRelatedValueList()
     bc, = base_category_list
     depth.pop()
     return [] if depth else [{bc: 'green'}]
     """)
   person = self.portal.person_module.newContent(reference=login)
   try:
     self.tic()
     PortalTestCase.login(self, person.Person_getUserId())
     self.assertEqual(['green'], getSecurityManager().getUser().getGroups())
     self.portal.portal_caches.clearAllCache()
     PortalTestCase.login(self, person.Person_getUserId())
     unittest.expectedFailure(self.assertEqual)(
       ['green'], getSecurityManager().getUser().getGroups())
   finally:
     skin.manage_delObjects(script_id)
     self.commit()
Exemplo n.º 3
0
  def test_put_file_twice_no_tic(self):
    self.postFile()
    self.commit()
    self.postFile()
    self.tic()

    document_list = self.portal.portal_catalog(reference=self.key)

    self.assertEqual(2, len(document_list))
    expectedFailure(self.assertEqual)(sorted(['archived', 'published']),
        sorted(q.getValidationState() for q in document_list))
 def test_03_03_load_using_bioformats_url(self):
     url = "https://github.com/CellProfiler/python-bioformats/raw/1.0.5/bioformats/tests/Channel1-01-A-01.tif"
     try:
         fd = urlopen(url)
         if fd.code < 200 or fd.code >= 300:
             raise OSError("Http error %d" % fd.code)
     except OSError as e:
         def bad_url(e=e):
             raise e
         unittest.expectedFailure(bad_url)()
     
     data = F.load_using_bioformats_url(url, rescale=False)
     self.assertSequenceEqual(data.shape, (640, 640))
Exemplo n.º 5
0
 def test_01_05_load_pipeline(self):
     import cellprofiler.pipeline as cpp
     import os
     def callback(caller, event):
         self.assertFalse(isinstance(event, cpp.LoadExceptionEvent))
     pipeline = cpp.Pipeline()
     pipeline.add_listener(callback)
     try:
         fd = urlopen(self.fly_url)
     except IOError, e:
         def bad_url(e=e):
             raise e
         unittest.expectedFailure(bad_url)()
def test_load_using_bioformats_url():
    url = "https://github.com/CellProfiler/python-bioformats/raw/1.0.5/bioformats/tests/Channel1-01-A-01.tif"
    try:
        fd = future.moves.urllib.request.urlopen(url)
        if fd.code < 200 or fd.code >= 300:
            raise OSError("Http error %d" % fd.code)
    except OSError as e:
        def bad_url(e=e):
            raise e
        unittest.expectedFailure(bad_url)()

    data = bioformats.formatreader.load_using_bioformats_url(url, rescale=False)
    assert data.shape == (640, 640)
Exemplo n.º 7
0
    def test_02_01_run_headless(self):
        output_directory = tempfile.mkdtemp()
        temp_directory = os.path.join(output_directory, "temp")
        os.mkdir(temp_directory)
        try:
            #
            # Run with a .cp file
            #
            fly_pipe = "http://cellprofiler.org/ExampleFlyImages/ExampleFlyURL.cppipe"
            urllib.URLopener().open(fly_pipe).close()
            measurements_file = os.path.join(output_directory, "Measurements.h5")
            done_file = os.path.join(output_directory, "Done.txt")
            self.run_cellprofiler(
                "-c",
                "-r",
                "-o",
                output_directory,
                "-p",
                fly_pipe,
                "-d",
                done_file,
                "-t",
                temp_directory,
                "-f",
                "1",
                "-l",
                "1",
                measurements_file,
            )
            import cellprofiler.preferences as cpprefs

            self.assertTrue(os.path.exists(measurements_file))
            self.assertTrue(os.path.exists(done_file))
            #
            # Re-run using the measurements file.
            #
            m2_file = os.path.join(output_directory, "M2.h5")
            self.run_cellprofiler(
                "-c", "-r", "-o", output_directory, "-f", "1", "-l", "1", "-p", measurements_file, m2_file
            )
            self.assertTrue(os.path.exists(m2_file))
        except IOError, e:
            if e.args[0] != "http error":
                raise e

            def bad_url(e=e):
                raise e

            unittest.expectedFailure(bad_url)()
Exemplo n.º 8
0
    def test_ResourceTags(self):
        # Host tags might not be present when using a v2 service
        if self.is_v2:
            return unittest.expectedFailure(self)

        topo = Topology()
        h1 = topo.source(host_name)
        h1.resource_tags.add('host1')
        
        h2 = topo.source(host_name)
        h2.resource_tags.add('host2')
        
        h = h1.union({h2})
        h.print()
        h = h.map(RemoveDup())

        h2sink = h2.for_each(lambda x : None, name='SinkOnHost1')
        h2sink.resource_tags.add('host1')

        beacon = Source(topo, "spl.utility::Beacon",
            'tuple<uint64 seq>',
            params = {'period': 0.02, 'iterations':100},
            name = 'BeaconOnHost1')
        beacon.seq = beacon.output('IterationCount()')
        beacon.resource_tags.add('host2')

        h2sinkNotags = h2.for_each(lambda x : None, name='SinkNoTags')
        self.assertFalse(h2sinkNotags.resource_tags)
        
        self.tester = Tester(topo)
        self.tester.tuple_count(h, 2)
        self.tester.local_check = self.check_placements
     
        sr = self.tester.test(self.test_ctxtype, self.test_config)
Exemplo n.º 9
0
 def f(func):
     rc = subprocess.call(['ip', 'link', 'add', 'dev', 'erspan99', 'type', 'erspan', 'seq', 'key', '30', 'local', '192.168.1.4', 'remote', '192.168.1.1', 'erspan_ver', '1', 'erspan', '123'])
     if rc == 0:
         subprocess.call(['ip', 'link', 'del', 'erspan99'])
         return func
     else:
         return unittest.expectedFailure(func)
Exemplo n.º 10
0
def create_test(input_file, output_file, thing):
    first_line = open(input_file, 'r').readline()
    def do_test(self):
        self.check_file(input_file, output_file, thing)
    if first_line.startswith('dnl fail') and thing == 'parser':
        return unittest.expectedFailure(do_test)
    return do_test
Exemplo n.º 11
0
def mark_tests_as_expected_failure(failing_tests):
    """
    Flag tests as expectedFailure. This should only run during the
    testsuite.
    """
    django_version = django.VERSION[:2]
    for test_name, versions in six.iteritems(failing_tests):
        if not versions or not isinstance(versions, (list, tuple)):
            # skip None, empty, or invalid
            continue
        if not isinstance(versions[0], (list, tuple)):
            # Ensure list of versions
            versions = [versions]
        if all(map(lambda v: v[:2] != django_version, versions)):
            continue
        test_case_name, _, method_name = test_name.rpartition('.')
        try:
            test_case = import_string(test_case_name)
        except ImproperlyConfigured:
            # Django tests might not be available during
            # testing of client code
            continue
        method = getattr(test_case, method_name)
        method = expectedFailure(method)
        setattr(test_case, method_name, method)
Exemplo n.º 12
0
def main():
    test_cases = list_delegation_tests(FIXTURE_ROOT)
    
    # Generate the 'constraint-solving-without-injection' tests.
    # These replace the TargetSolverNoInjection tests we used to have in test.py.
    constraint_solved_tests = {
            "eq": {
                #"Concolic::Solver::ErrorsReadingSolution": "0",    # Error by default, don't neet to test explicitly.
                #"Concolic::Solver::ConstraintsSolvedAsUNSAT": "0", # Error by default, don't neet to test explicitly.
                #"Concolic::Solver::ConstraintsNotSolved": "0",     # Error by default, don't neet to test explicitly.
                "Concolic::Solver::ConstraintsSolved": "1"
            }
        }
    
    for t in test_cases:
        test_name = 'test_constraint-solving-without-injection_%s' % t['name']
        file_name = "%s%s" % (FIXTURE_ROOT, t['fn'])
        test = concolic.test_generator(_artemis_runner_no_injections, file_name, test_name, test_dict=constraint_solved_tests, internal_test=None)
        setattr(EventDelegation, test_name, test)
    
    # Generate the tests which check for the assertions included in the test suite.
    for t in test_cases:
        test_name = 'test_%s' % t['name']
        file_name = "%s%s" % (FIXTURE_ROOT, t['fn'])
        
        test = concolic.test_generator(_artemis_runner_full, file_name, test_name, test_dict=t['test'], internal_test=t['i_test'])
        
        if t['expected_failure']:
            test = unittest.expectedFailure(test)
        
        setattr(EventDelegation, test_name, test)
    
    unittest.main(buffer=True, catchbreak=True)
Exemplo n.º 13
0
def maybe_download_tesst_image( file_name):
    '''Download the given TestImages file if not in the directory

    file_name - name of file to fetch

    Image will be downloaded if not present to CP_EXAMPLEIMAGES directory.
    '''
    local_path = os.path.join(testimages_directory(), file_name)
    if not os.path.exists(local_path):
        url = testimages_url() + "/" + file_name
        try:
            URLopener().retrieve(url, local_path)
        except IOError, e:
            # This raises the "expected failure" exception.
            def bad_url(e=e):
                raise e
            unittest.expectedFailure(bad_url)()
Exemplo n.º 14
0
def implements(commands, expectedFailure=False):  # noqa: N803
    def _test(self):
        with self.run_bpd() as client:
            response = client.send_command('commands')
        self._assert_ok(response)
        implemented = response.data['command']
        self.assertEqual(commands.intersection(implemented), commands)
    return unittest.expectedFailure(_test) if expectedFailure else _test
Exemplo n.º 15
0
def cxOracle_py3_bug(func):
    """
    There's a bug in Django/cx_Oracle with respect to string handling under
    Python 3 (essentially, they treat Python 3 strings as Python 2 strings
    rather than unicode). This makes some tests here fail under Python 3, so
    we mark them as expected failures until someone fixes them in #23843.
    """
    from unittest import expectedFailure
    from django.db import connection
    return expectedFailure(func) if connection.vendor == 'oracle' else func
Exemplo n.º 16
0
def _addTests():
    for path in glob.glob(os.path.join(drawBotScriptDir, "*.py")):
        scriptName = os.path.splitext(os.path.basename(path))[0]
        for ext in testExt:
            testMethodName = "test_%s_%s" % (ext, scriptName)
            testMethod = makeTestCase(path, ext, testMethodName in ignoreDeprecationWarnings)
            testMethod.__name__ = testMethodName
            if testMethodName in expectedFailures:
                testMethod = unittest.expectedFailure(testMethod)
            setattr(DrawBotTest, testMethodName, testMethod)
Exemplo n.º 17
0
def expectedFailureIfAppengine(func):
    try:
        from google import appengine
    except ImportError:
        return func
    else:
        import os

        if os.environ.get('SERVER_SOFTWARE', None) is None:
            return func

        return unittest.expectedFailure(func)
Exemplo n.º 18
0
def cxOracle_513_py3_bug(func):
    """
    cx_Oracle versions up to and including 5.1.3 have a bug with respect to
    string handling under Python3 (essentially, they treat Python3 strings
    as Python2 strings rather than unicode). This makes some tests here
    fail under Python 3 -- so we mark them as expected failures.

    See  https://code.djangoproject.com/ticket/23843, in particular comment 6,
    which points to https://bitbucket.org/anthony_tuininga/cx_oracle/issue/6/
    """
    from unittest import expectedFailure
    from django.db import connection

    if connection.vendor == 'oracle' and six.PY3 and connection.Database.version <= '5.1.3':
        return expectedFailure(func)
    else:
        return func
Exemplo n.º 19
0
def _addExampleTests():
    allExamples = _collectExamples([
        DrawBotDrawingTool,
        DrawBotDrawingTool._formattedStringClass,
        DrawBotDrawingTool._bezierPathClass,
        DrawBotDrawingTool._imageClass
    ])

    for exampleName, source in allExamples.items():
        testMethodName = "test_%s" % exampleName
        testMethod = _makeTestCase(exampleName, source, doSaveImage=testMethodName not in dontSaveImage,
                allowFuzzyImageComparison=testMethodName in allowFuzzyImageComparison)
        testMethod.__name__ = testMethodName
        if testMethodName in skip:
            continue
        if testMethodName in expectedFailures:
            testMethod = unittest.expectedFailure(testMethod)
        setattr(ExampleTester, testMethodName, testMethod)
Exemplo n.º 20
0
  def catalog(self, reference_tree, kw, check_search_text=True,
      check_select_expression=True, expected_failure=False):
    reference_param_dict = self._catalog._queryResults(query_table='foo', **kw)
    query = self._catalog.buildQuery(kw)
    assertEqual = self.assertEqual
    if expected_failure:
      assertEqual = unittest.expectedFailure(assertEqual)

    assertEqual(reference_tree, query)
    search_text = query.asSearchTextExpression(self._catalog)
    if check_search_text:
      # XXX: sould "keyword" be always used for search text searches ?
      search_text_param_dict = self._catalog._queryResults(query_table='foo', keyword=search_text)
      if not check_select_expression:
        search_text_param_dict.pop('select_expression')
        reference_param_dict.pop('select_expression')
      assertEqual(reference_param_dict, search_text_param_dict,
          'Query: %r\nSearchText: %r\nReference: %r\nSecond rendering: %r' % \
                       (query, search_text, reference_param_dict, search_text_param_dict))
Exemplo n.º 21
0
 def f(func):
     if not is_module_available(module_name):
         return unittest.expectedFailure(func)
     return func
Exemplo n.º 22
0
class DefaultFiltersTests(TestCase):
    def test_floatformat(self):
        self.assertEqual(floatformat(7.7), '7.7')
        self.assertEqual(floatformat(7.0), '7')
        self.assertEqual(floatformat(0.7), '0.7')
        self.assertEqual(floatformat(0.07), '0.1')
        self.assertEqual(floatformat(0.007), '0.0')
        self.assertEqual(floatformat(0.0), '0')
        self.assertEqual(floatformat(7.7, 3), '7.700')
        self.assertEqual(floatformat(6.000000, 3), '6.000')
        self.assertEqual(floatformat(6.200000, 3), '6.200')
        self.assertEqual(floatformat(6.200000, -3), '6.200')
        self.assertEqual(floatformat(13.1031, -3), '13.103')
        self.assertEqual(floatformat(11.1197, -2), '11.12')
        self.assertEqual(floatformat(11.0000, -2), '11')
        self.assertEqual(floatformat(11.000001, -2), '11.00')
        self.assertEqual(floatformat(8.2798, 3), '8.280')
        self.assertEqual(floatformat(5555.555, 2), '5555.56')
        self.assertEqual(floatformat(001.3000, 2), '1.30')
        self.assertEqual(floatformat(0.12345, 2), '0.12')
        self.assertEqual(floatformat(decimal.Decimal('555.555'), 2), '555.56')
        self.assertEqual(floatformat(decimal.Decimal('09.000')), '9')
        self.assertEqual(floatformat('foo'), '')
        self.assertEqual(floatformat(13.1031, 'bar'), '13.1031')
        self.assertEqual(floatformat(18.125, 2), '18.13')
        self.assertEqual(floatformat('foo', 'bar'), '')
        self.assertEqual(floatformat('¿Cómo esta usted?'), '')
        self.assertEqual(floatformat(None), '')

        # Check that we're not converting to scientific notation.
        self.assertEqual(floatformat(0, 6), '0.000000')
        self.assertEqual(floatformat(0, 7), '0.0000000')
        self.assertEqual(floatformat(0, 10), '0.0000000000')
        self.assertEqual(floatformat(0.000000000000000000015, 20),
                         '0.00000000000000000002')

        pos_inf = float(1e30000)
        self.assertEqual(floatformat(pos_inf), six.text_type(pos_inf))

        neg_inf = float(-1e30000)
        self.assertEqual(floatformat(neg_inf), six.text_type(neg_inf))

        nan = pos_inf / pos_inf
        self.assertEqual(floatformat(nan), six.text_type(nan))

        class FloatWrapper(object):
            def __init__(self, value):
                self.value = value

            def __float__(self):
                return self.value

        self.assertEqual(floatformat(FloatWrapper(11.000001), -2), '11.00')

        # Regression for #15789
        decimal_ctx = decimal.getcontext()
        old_prec, decimal_ctx.prec = decimal_ctx.prec, 2
        try:
            self.assertEqual(floatformat(1.2345, 2), '1.23')
            self.assertEqual(floatformat(15.2042, -3), '15.204')
            self.assertEqual(floatformat(1.2345, '2'), '1.23')
            self.assertEqual(floatformat(15.2042, '-3'), '15.204')
            self.assertEqual(floatformat(decimal.Decimal('1.2345'), 2), '1.23')
            self.assertEqual(floatformat(decimal.Decimal('15.2042'), -3),
                             '15.204')
        finally:
            decimal_ctx.prec = old_prec

    def test_floatformat_py2_fail(self):
        self.assertEqual(floatformat(1.00000000000000015, 16),
                         '1.0000000000000002')

    # The test above fails because of Python 2's float handling. Floats with
    # many zeroes after the decimal point should be passed in as another type
    # such as unicode or Decimal.
    if not six.PY3:
        test_floatformat_py2_fail = unittest.expectedFailure(
            test_floatformat_py2_fail)

    def test_addslashes(self):
        self.assertEqual(addslashes('"double quotes" and \'single quotes\''),
                         '\\"double quotes\\" and \\\'single quotes\\\'')

        self.assertEqual(addslashes(r'\ : backslashes, too'),
                         '\\\\ : backslashes, too')

    def test_capfirst(self):
        self.assertEqual(capfirst('hello world'), 'Hello world')

    def test_escapejs(self):
        self.assertEqual(
            escapejs_filter('"double quotes" and \'single quotes\''),
            '\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027')
        self.assertEqual(escapejs_filter(r'\ : backslashes, too'),
                         '\\u005C : backslashes, too')
        self.assertEqual(
            escapejs_filter('and lots of whitespace: \r\n\t\v\f\b'),
            'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008'
        )
        self.assertEqual(escapejs_filter(r'<script>and this</script>'),
                         '\\u003Cscript\\u003Eand this\\u003C/script\\u003E')
        self.assertEqual(
            escapejs_filter(
                'paragraph separator:\u2029and line separator:\u2028'),
            'paragraph separator:\\u2029and line separator:\\u2028')

    def test_fix_ampersands(self):
        self.assertEqual(fix_ampersands_filter('Jack & Jill & Jeroboam'),
                         'Jack &amp; Jill &amp; Jeroboam')

    def test_linenumbers(self):
        self.assertEqual(linenumbers('line 1\nline 2'), '1. line 1\n2. line 2')
        self.assertEqual(linenumbers('\n'.join(['x'] * 10)),
                          '01. x\n02. x\n03. x\n04. x\n05. x\n06. x\n07. '\
                          'x\n08. x\n09. x\n10. x')

    def test_lower(self):
        self.assertEqual(lower('TEST'), 'test')

        # uppercase E umlaut
        self.assertEqual(lower('\xcb'), '\xeb')

    def test_make_list(self):
        self.assertEqual(make_list('abc'), ['a', 'b', 'c'])
        self.assertEqual(make_list(1234), ['1', '2', '3', '4'])

    def test_slugify(self):
        self.assertEqual(slugify(' Jack & Jill like numbers 1,2,3 and 4 and'\
            ' silly characters ?%.$!/'),
            'jack-jill-like-numbers-123-and-4-and-silly-characters')

        self.assertEqual(slugify("Un \xe9l\xe9phant \xe0 l'or\xe9e du bois"),
                         'un-elephant-a-loree-du-bois')

    def test_stringformat(self):
        self.assertEqual(stringformat(1, '03d'), '001')
        self.assertEqual(stringformat(1, 'z'), '')

    def test_title(self):
        self.assertEqual(title('a nice title, isn\'t it?'),
                         "A Nice Title, Isn't It?")
        self.assertEqual(title('discoth\xe8que'), 'Discoth\xe8que')

    def test_truncatewords(self):
        self.assertEqual(truncatewords('A sentence with a few words in it', 1),
                         'A ...')
        self.assertEqual(truncatewords('A sentence with a few words in it', 5),
                         'A sentence with a few ...')
        self.assertEqual(
            truncatewords('A sentence with a few words in it', 100),
            'A sentence with a few words in it')
        self.assertEqual(
            truncatewords('A sentence with a few words in it', 'not a number'),
            'A sentence with a few words in it')

    def test_truncatewords_html(self):
        self.assertEqual(
            truncatewords_html(
                '<p>one <a href="#">two - three <br>four</a> five</p>', 0), '')
        self.assertEqual(truncatewords_html('<p>one <a href="#">two - '\
            'three <br>four</a> five</p>', 2),
            '<p>one <a href="#">two ...</a></p>')
        self.assertEqual(
            truncatewords_html(
                '<p>one <a href="#">two - three <br>four</a> five</p>', 4),
            '<p>one <a href="#">two - three <br>four ...</a></p>')
        self.assertEqual(
            truncatewords_html(
                '<p>one <a href="#">two - three <br>four</a> five</p>', 5),
            '<p>one <a href="#">two - three <br>four</a> five</p>')
        self.assertEqual(
            truncatewords_html(
                '<p>one <a href="#">two - three <br>four</a> five</p>', 100),
            '<p>one <a href="#">two - three <br>four</a> five</p>')
        self.assertEqual(truncatewords_html('\xc5ngstr\xf6m was here', 1),
                         '\xc5ngstr\xf6m ...')

    def test_upper(self):
        self.assertEqual(upper('Mixed case input'), 'MIXED CASE INPUT')
        # lowercase e umlaut
        self.assertEqual(upper('\xeb'), '\xcb')

    def test_urlencode(self):
        self.assertEqual(urlencode('fran\xe7ois & jill'),
                         'fran%C3%A7ois%20%26%20jill')
        self.assertEqual(urlencode(1), '1')

    def test_iriencode(self):
        self.assertEqual(iriencode('S\xf8r-Tr\xf8ndelag'),
                         'S%C3%B8r-Tr%C3%B8ndelag')
        self.assertEqual(iriencode(urlencode('fran\xe7ois & jill')),
                         'fran%C3%A7ois%20%26%20jill')

    def test_urlizetrunc(self):
        self.assertEqual(urlizetrunc('http://short.com/', 20), '<a href='\
            '"http://short.com/" rel="nofollow">http://short.com/</a>')

        self.assertEqual(urlizetrunc('http://www.google.co.uk/search?hl=en'\
            '&q=some+long+url&btnG=Search&meta=', 20), '<a href="http://'\
            'www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&'\
            'meta=" rel="nofollow">http://www.google...</a>')

        self.assertEqual(urlizetrunc('http://www.google.co.uk/search?hl=en'\
            '&q=some+long+url&btnG=Search&meta=', 20), '<a href="http://'\
            'www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search'\
            '&meta=" rel="nofollow">http://www.google...</a>')

        # Check truncating of URIs which are the exact length
        uri = 'http://31characteruri.com/test/'
        self.assertEqual(len(uri), 31)

        self.assertEqual(urlizetrunc(uri, 31),
            '<a href="http://31characteruri.com/test/" rel="nofollow">'\
            'http://31characteruri.com/test/</a>')

        self.assertEqual(urlizetrunc(uri, 30),
            '<a href="http://31characteruri.com/test/" rel="nofollow">'\
            'http://31characteruri.com/t...</a>')

        self.assertEqual(urlizetrunc(uri, 2),
            '<a href="http://31characteruri.com/test/"'\
            ' rel="nofollow">...</a>')

    def test_urlize(self):
        # Check normal urlize
        self.assertEqual(
            urlize('http://google.com'),
            '<a href="http://google.com" rel="nofollow">http://google.com</a>')
        self.assertEqual(
            urlize('http://google.com/'),
            '<a href="http://google.com/" rel="nofollow">http://google.com/</a>'
        )
        self.assertEqual(
            urlize('www.google.com'),
            '<a href="http://www.google.com" rel="nofollow">www.google.com</a>'
        )
        self.assertEqual(
            urlize('djangoproject.org'),
            '<a href="http://djangoproject.org" rel="nofollow">djangoproject.org</a>'
        )
        self.assertEqual(
            urlize('*****@*****.**'),
            '<a href="mailto:[email protected]">[email protected]</a>'
        )

        # Check urlize with https addresses
        self.assertEqual(
            urlize('https://google.com'),
            '<a href="https://google.com" rel="nofollow">https://google.com</a>'
        )

        # Check urlize doesn't overquote already quoted urls - see #9655
        self.assertEqual(
            urlize('http://hi.baidu.com/%D6%D8%D0%C2%BF'),
            '<a href="http://hi.baidu.com/%D6%D8%D0%C2%BF" rel="nofollow">'
            'http://hi.baidu.com/%D6%D8%D0%C2%BF</a>')
        self.assertEqual(
            urlize('www.mystore.com/30%OffCoupons!'),
            '<a href="http://www.mystore.com/30%25OffCoupons!" rel="nofollow">'
            'www.mystore.com/30%OffCoupons!</a>')
        self.assertEqual(
            urlize('http://en.wikipedia.org/wiki/Caf%C3%A9'),
            '<a href="http://en.wikipedia.org/wiki/Caf%C3%A9" rel="nofollow">'
            'http://en.wikipedia.org/wiki/Caf%C3%A9</a>')
        self.assertEqual(
            urlize('http://en.wikipedia.org/wiki/Café'),
            '<a href="http://en.wikipedia.org/wiki/Caf%C3%A9" rel="nofollow">'
            'http://en.wikipedia.org/wiki/Café</a>')

        # Check urlize keeps balanced parentheses - see #11911
        self.assertEqual(
            urlize('http://en.wikipedia.org/wiki/Django_(web_framework)'),
            '<a href="http://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">'
            'http://en.wikipedia.org/wiki/Django_(web_framework)</a>')
        self.assertEqual(
            urlize(
                '(see http://en.wikipedia.org/wiki/Django_(web_framework))'),
            '(see <a href="http://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">'
            'http://en.wikipedia.org/wiki/Django_(web_framework)</a>)')

        # Check urlize adds nofollow properly - see #12183
        self.assertEqual(
            urlize('[email protected] or www.bar.com'),
            '<a href="mailto:[email protected]">[email protected]</a> or '
            '<a href="http://www.bar.com" rel="nofollow">www.bar.com</a>')

        # Check urlize handles IDN correctly - see #13704
        self.assertEqual(
            urlize('http://c✶.ws'),
            '<a href="http://xn--c-lgq.ws" rel="nofollow">http://c✶.ws</a>')
        self.assertEqual(
            urlize('www.c✶.ws'),
            '<a href="http://www.xn--c-lgq.ws" rel="nofollow">www.c✶.ws</a>')
        self.assertEqual(
            urlize('c✶.org'),
            '<a href="http://xn--c-lgq.org" rel="nofollow">c✶.org</a>')
        self.assertEqual(
            urlize('info@c✶.org'),
            '<a href="mailto:[email protected]">info@c✶.org</a>')

        # Check urlize doesn't highlight malformed URIs - see #16395
        self.assertEqual(urlize('http:///www.google.com'),
                         'http:///www.google.com')
        self.assertEqual(urlize('http://.google.com'), 'http://.google.com')
        self.assertEqual(urlize('http://@foo.com'), 'http://@foo.com')

        # Check urlize accepts more TLDs - see #16656
        self.assertEqual(
            urlize('usa.gov'),
            '<a href="http://usa.gov" rel="nofollow">usa.gov</a>')

        # Check urlize don't crash on invalid email with dot-starting domain - see #17592
        self.assertEqual(urlize('*****@*****.**'), '*****@*****.**')

        # Check urlize accepts uppercased URL schemes - see #18071
        self.assertEqual(
            urlize('HTTPS://github.com/'),
            '<a href="https://github.com/" rel="nofollow">HTTPS://github.com/</a>'
        )

        # Check urlize trims trailing period when followed by parenthesis - see #18644
        self.assertEqual(
            urlize('(Go to http://www.example.com/foo.)'),
            '(Go to <a href="http://www.example.com/foo" rel="nofollow">http://www.example.com/foo</a>.)'
        )

        # Check urlize handles brackets properly (#19070)
        self.assertEqual(
            urlize('[see www.example.com]'),
            '[see <a href="http://www.example.com" rel="nofollow">www.example.com</a>]'
        )
        self.assertEqual(
            urlize('see test[at[example.com'),
            'see <a href="http://test[at[example.com" rel="nofollow">test[at[example.com</a>'
        )
        self.assertEqual(
            urlize('[http://168.192.0.1](http://168.192.0.1)'),
            '[<a href="http://168.192.0.1](http://168.192.0.1)" rel="nofollow">http://168.192.0.1](http://168.192.0.1)</a>'
        )

        # Check urlize works with IPv4/IPv6 addresses
        self.assertEqual(
            urlize('http://192.168.0.15/api/9'),
            '<a href="http://192.168.0.15/api/9" rel="nofollow">http://192.168.0.15/api/9</a>'
        )
        self.assertEqual(
            urlize('http://[2001:db8:cafe::2]/api/9'),
            '<a href="http://[2001:db8:cafe::2]/api/9" rel="nofollow">http://[2001:db8:cafe::2]/api/9</a>'
        )

    def test_wordcount(self):
        self.assertEqual(wordcount(''), 0)
        self.assertEqual(wordcount('oneword'), 1)
        self.assertEqual(wordcount('lots of words'), 3)

        self.assertEqual(wordwrap('this is a long paragraph of text that '\
            'really needs to be wrapped I\'m afraid', 14),
            "this is a long\nparagraph of\ntext that\nreally needs\nto be "\
            "wrapped\nI'm afraid")

        self.assertEqual(wordwrap('this is a short paragraph of text.\n  '\
            'But this line should be indented', 14),
            'this is a\nshort\nparagraph of\ntext.\n  But this\nline '\
            'should be\nindented')

        self.assertEqual(wordwrap('this is a short paragraph of text.\n  '\
            'But this line should be indented',15), 'this is a short\n'\
            'paragraph of\ntext.\n  But this line\nshould be\nindented')

    def test_rjust(self):
        self.assertEqual(ljust('test', 10), 'test      ')
        self.assertEqual(ljust('test', 3), 'test')
        self.assertEqual(rjust('test', 10), '      test')
        self.assertEqual(rjust('test', 3), 'test')

    def test_center(self):
        self.assertEqual(center('test', 6), ' test ')

    def test_cut(self):
        self.assertEqual(cut('a string to be mangled', 'a'),
                         ' string to be mngled')
        self.assertEqual(cut('a string to be mangled', 'ng'),
                         'a stri to be maled')
        self.assertEqual(cut('a string to be mangled', 'strings'),
                         'a string to be mangled')

    def test_force_escape(self):
        escaped = force_escape('<some html & special characters > here')
        self.assertEqual(escaped,
                         '&lt;some html &amp; special characters &gt; here')
        self.assertIsInstance(escaped, SafeData)
        self.assertEqual(
            force_escape('<some html & special characters > here ĐÅ€£'),
            '&lt;some html &amp; special characters &gt; here'\
            ' \u0110\xc5\u20ac\xa3')

    def test_linebreaks(self):
        self.assertEqual(linebreaks_filter('line 1'), '<p>line 1</p>')
        self.assertEqual(linebreaks_filter('line 1\nline 2'),
                         '<p>line 1<br />line 2</p>')
        self.assertEqual(linebreaks_filter('line 1\rline 2'),
                         '<p>line 1<br />line 2</p>')
        self.assertEqual(linebreaks_filter('line 1\r\nline 2'),
                         '<p>line 1<br />line 2</p>')

    def test_linebreaksbr(self):
        self.assertEqual(linebreaksbr('line 1\nline 2'), 'line 1<br />line 2')
        self.assertEqual(linebreaksbr('line 1\rline 2'), 'line 1<br />line 2')
        self.assertEqual(linebreaksbr('line 1\r\nline 2'),
                         'line 1<br />line 2')

    def test_removetags(self):
        self.assertEqual(removetags('some <b>html</b> with <script>alert'\
            '("You smell")</script> disallowed <img /> tags', 'script img'),
            'some <b>html</b> with alert("You smell") disallowed  tags')
        self.assertEqual(striptags('some <b>html</b> with <script>alert'\
            '("You smell")</script> disallowed <img /> tags'),
            'some html with alert("You smell") disallowed  tags')

    def test_dictsort(self):
        sorted_dicts = dictsort([{
            'age': 23,
            'name': 'Barbara-Ann'
        }, {
            'age': 63,
            'name': 'Ra Ra Rasputin'
        }, {
            'name': 'Jonny B Goode',
            'age': 18
        }], 'age')

        self.assertEqual([sorted(dict.items()) for dict in sorted_dicts], [[
            ('age', 18), ('name', 'Jonny B Goode')
        ], [('age', 23),
            ('name', 'Barbara-Ann')], [('age', 63),
                                       ('name', 'Ra Ra Rasputin')]])

        # If it gets passed a list of something else different from
        # dictionaries it should fail silently
        self.assertEqual(dictsort([1, 2, 3], 'age'), '')
        self.assertEqual(dictsort('Hello!', 'age'), '')
        self.assertEqual(dictsort({'a': 1}, 'age'), '')
        self.assertEqual(dictsort(1, 'age'), '')

    def test_dictsortreversed(self):
        sorted_dicts = dictsortreversed([{
            'age': 23,
            'name': 'Barbara-Ann'
        }, {
            'age': 63,
            'name': 'Ra Ra Rasputin'
        }, {
            'name': 'Jonny B Goode',
            'age': 18
        }], 'age')

        self.assertEqual([sorted(dict.items()) for dict in sorted_dicts], [[
            ('age', 63), ('name', 'Ra Ra Rasputin')
        ], [('age', 23),
            ('name', 'Barbara-Ann')], [('age', 18),
                                       ('name', 'Jonny B Goode')]])

        # If it gets passed a list of something else different from
        # dictionaries it should fail silently
        self.assertEqual(dictsortreversed([1, 2, 3], 'age'), '')
        self.assertEqual(dictsortreversed('Hello!', 'age'), '')
        self.assertEqual(dictsortreversed({'a': 1}, 'age'), '')
        self.assertEqual(dictsortreversed(1, 'age'), '')

    def test_first(self):
        self.assertEqual(first([0, 1, 2]), 0)
        self.assertEqual(first(''), '')
        self.assertEqual(first('test'), 't')

    def test_join(self):
        self.assertEqual(join([0, 1, 2], 'glue'), '0glue1glue2')

    def test_length(self):
        self.assertEqual(length('1234'), 4)
        self.assertEqual(length([1, 2, 3, 4]), 4)
        self.assertEqual(length_is([], 0), True)
        self.assertEqual(length_is([], 1), False)
        self.assertEqual(length_is('a', 1), True)
        self.assertEqual(length_is('a', 10), False)

    def test_slice(self):
        self.assertEqual(slice_filter('abcdefg', '0'), '')
        self.assertEqual(slice_filter('abcdefg', '1'), 'a')
        self.assertEqual(slice_filter('abcdefg', '-1'), 'abcdef')
        self.assertEqual(slice_filter('abcdefg', '1:2'), 'b')
        self.assertEqual(slice_filter('abcdefg', '1:3'), 'bc')
        self.assertEqual(slice_filter('abcdefg', '0::2'), 'aceg')

    def test_unordered_list(self):
        self.assertEqual(unordered_list(['item 1', 'item 2']),
                         '\t<li>item 1</li>\n\t<li>item 2</li>')
        self.assertEqual(
            unordered_list(['item 1', ['item 1.1']]),
            '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>')

        self.assertEqual(
            unordered_list(['item 1', ['item 1.1', 'item1.2'], 'item 2']),
            '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t\t<li>item1.2'\
            '</li>\n\t</ul>\n\t</li>\n\t<li>item 2</li>')

        self.assertEqual(
            unordered_list(['item 1', ['item 1.1', ['item 1.1.1',
                                                      ['item 1.1.1.1']]]]),
            '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1\n\t\t<ul>\n\t\t\t<li>'\
            'item 1.1.1\n\t\t\t<ul>\n\t\t\t\t<li>item 1.1.1.1</li>\n\t\t\t'\
            '</ul>\n\t\t\t</li>\n\t\t</ul>\n\t\t</li>\n\t</ul>\n\t</li>')

        self.assertEqual(unordered_list(
            ['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]),
            '\t<li>States\n\t<ul>\n\t\t<li>Kansas\n\t\t<ul>\n\t\t\t<li>'\
            'Lawrence</li>\n\t\t\t<li>Topeka</li>\n\t\t</ul>\n\t\t</li>'\
            '\n\t\t<li>Illinois</li>\n\t</ul>\n\t</li>')

        @python_2_unicode_compatible
        class ULItem(object):
            def __init__(self, title):
                self.title = title

            def __str__(self):
                return 'ulitem-%s' % str(self.title)

        a = ULItem('a')
        b = ULItem('b')
        self.assertEqual(unordered_list([a, b]),
                         '\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>')

        # Old format for unordered lists should still work
        self.assertEqual(unordered_list(['item 1', []]), '\t<li>item 1</li>')

        self.assertEqual(
            unordered_list(['item 1', [['item 1.1', []]]]),
            '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>')

        self.assertEqual(unordered_list(['item 1', [['item 1.1', []],
            ['item 1.2', []]]]), '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1'\
            '</li>\n\t\t<li>item 1.2</li>\n\t</ul>\n\t</li>')

        self.assertEqual(unordered_list(['States', [['Kansas', [['Lawrence',
            []], ['Topeka', []]]], ['Illinois', []]]]), '\t<li>States\n\t'\
            '<ul>\n\t\t<li>Kansas\n\t\t<ul>\n\t\t\t<li>Lawrence</li>'\
            '\n\t\t\t<li>Topeka</li>\n\t\t</ul>\n\t\t</li>\n\t\t<li>'\
            'Illinois</li>\n\t</ul>\n\t</li>')

    def test_add(self):
        self.assertEqual(add('1', '2'), 3)

    def test_get_digit(self):
        self.assertEqual(get_digit(123, 1), 3)
        self.assertEqual(get_digit(123, 2), 2)
        self.assertEqual(get_digit(123, 3), 1)
        self.assertEqual(get_digit(123, 4), 0)
        self.assertEqual(get_digit(123, 0), 123)
        self.assertEqual(get_digit('xyz', 0), 'xyz')

    def test_date(self):
        # real testing of date() is in dateformat.py
        self.assertEqual(date(datetime.datetime(2005, 12, 29), "d F Y"),
                         '29 December 2005')
        self.assertEqual(date(datetime.datetime(2005, 12, 29), r'jS \o\f F'),
                         '29th of December')

    def test_time(self):
        # real testing of time() is done in dateformat.py
        self.assertEqual(time(datetime.time(13), "h"), '01')
        self.assertEqual(time(datetime.time(0), "h"), '12')

    def test_timesince(self):
        # real testing is done in timesince.py, where we can provide our own 'now'
        # NOTE: \xa0 avoids wrapping between value and unit
        self.assertEqual(
            timesince_filter(datetime.datetime.now() - datetime.timedelta(1)),
            '1\xa0day')

        self.assertEqual(
            timesince_filter(datetime.datetime(2005, 12, 29),
                             datetime.datetime(2005, 12, 30)), '1\xa0day')

    def test_timeuntil(self):
        # NOTE: \xa0 avoids wrapping between value and unit
        self.assertEqual(
            timeuntil_filter(datetime.datetime.now() +
                             datetime.timedelta(1, 1)), '1\xa0day')

        self.assertEqual(
            timeuntil_filter(datetime.datetime(2005, 12, 30),
                             datetime.datetime(2005, 12, 29)), '1\xa0day')

    def test_default(self):
        self.assertEqual(default("val", "default"), 'val')
        self.assertEqual(default(None, "default"), 'default')
        self.assertEqual(default('', "default"), 'default')

    def test_if_none(self):
        self.assertEqual(default_if_none("val", "default"), 'val')
        self.assertEqual(default_if_none(None, "default"), 'default')
        self.assertEqual(default_if_none('', "default"), '')

    def test_divisibleby(self):
        self.assertEqual(divisibleby(4, 2), True)
        self.assertEqual(divisibleby(4, 3), False)

    def test_yesno(self):
        self.assertEqual(yesno(True), 'yes')
        self.assertEqual(yesno(False), 'no')
        self.assertEqual(yesno(None), 'maybe')
        self.assertEqual(yesno(True, 'certainly,get out of town,perhaps'),
                         'certainly')
        self.assertEqual(yesno(False, 'certainly,get out of town,perhaps'),
                         'get out of town')
        self.assertEqual(yesno(None, 'certainly,get out of town,perhaps'),
                         'perhaps')
        self.assertEqual(yesno(None, 'certainly,get out of town'),
                         'get out of town')

    def test_filesizeformat(self):
        # NOTE: \xa0 avoids wrapping between value and unit
        self.assertEqual(filesizeformat(1023), '1023\xa0bytes')
        self.assertEqual(filesizeformat(1024), '1.0\xa0KB')
        self.assertEqual(filesizeformat(10 * 1024), '10.0\xa0KB')
        self.assertEqual(filesizeformat(1024 * 1024 - 1), '1024.0\xa0KB')
        self.assertEqual(filesizeformat(1024 * 1024), '1.0\xa0MB')
        self.assertEqual(filesizeformat(1024 * 1024 * 50), '50.0\xa0MB')
        self.assertEqual(filesizeformat(1024 * 1024 * 1024 - 1),
                         '1024.0\xa0MB')
        self.assertEqual(filesizeformat(1024 * 1024 * 1024), '1.0\xa0GB')
        self.assertEqual(filesizeformat(1024 * 1024 * 1024 * 1024),
                         '1.0\xa0TB')
        self.assertEqual(filesizeformat(1024 * 1024 * 1024 * 1024 * 1024),
                         '1.0\xa0PB')
        self.assertEqual(
            filesizeformat(1024 * 1024 * 1024 * 1024 * 1024 * 2000),
            '2000.0\xa0PB')
        self.assertEqual(filesizeformat(complex(1, -1)), '0\xa0bytes')
        self.assertEqual(filesizeformat(""), '0\xa0bytes')
        self.assertEqual(filesizeformat("\N{GREEK SMALL LETTER ALPHA}"),
                         '0\xa0bytes')

    def test_pluralize(self):
        self.assertEqual(pluralize(1), '')
        self.assertEqual(pluralize(0), 's')
        self.assertEqual(pluralize(2), 's')
        self.assertEqual(pluralize([1]), '')
        self.assertEqual(pluralize([]), 's')
        self.assertEqual(pluralize([1, 2, 3]), 's')
        self.assertEqual(pluralize(1, 'es'), '')
        self.assertEqual(pluralize(0, 'es'), 'es')
        self.assertEqual(pluralize(2, 'es'), 'es')
        self.assertEqual(pluralize(1, 'y,ies'), 'y')
        self.assertEqual(pluralize(0, 'y,ies'), 'ies')
        self.assertEqual(pluralize(2, 'y,ies'), 'ies')
        self.assertEqual(pluralize(0, 'y,ies,error'), '')

    def test_phone2numeric(self):
        self.assertEqual(phone2numeric_filter('0800 flowers'), '0800 3569377')

    def test_non_string_input(self):
        # Filters shouldn't break if passed non-strings
        self.assertEqual(addslashes(123), '123')
        self.assertEqual(linenumbers(123), '1. 123')
        self.assertEqual(lower(123), '123')
        self.assertEqual(make_list(123), ['1', '2', '3'])
        self.assertEqual(slugify(123), '123')
        self.assertEqual(title(123), '123')
        self.assertEqual(truncatewords(123, 2), '123')
        self.assertEqual(upper(123), '123')
        self.assertEqual(urlencode(123), '123')
        self.assertEqual(urlize(123), '123')
        self.assertEqual(urlizetrunc(123, 1), '123')
        self.assertEqual(wordcount(123), 1)
        self.assertEqual(wordwrap(123, 2), '123')
        self.assertEqual(ljust('123', 4), '123 ')
        self.assertEqual(rjust('123', 4), ' 123')
        self.assertEqual(center('123', 5), ' 123 ')
        self.assertEqual(center('123', 6), ' 123  ')
        self.assertEqual(cut(123, '2'), '13')
        self.assertEqual(escape(123), '123')
        self.assertEqual(linebreaks_filter(123), '<p>123</p>')
        self.assertEqual(linebreaksbr(123), '123')
        self.assertEqual(removetags(123, 'a'), '123')
        self.assertEqual(striptags(123), '123')
Exemplo n.º 23
0
class AdminTests(TestCase):
    def setUp(self):
        today = datetime.date.today()
        self.album = Album.objects.create(category='default',
                                          dirpath='foo',
                                          date=today)
        self.album2 = Album.objects.create(category='default',
                                           dirpath='foo2',
                                           date=today)
        AlbumAccessPolicy.objects.create(album=self.album,
                                         public=True,
                                         inherit=False)
        self.photo = Photo.objects.create(album=self.album, filename='bar')
        self.photo2 = Photo.objects.create(album=self.album, filename='bar2')
        PhotoAccessPolicy.objects.create(photo=self.photo, public=True)
        self.user = User.objects.create_superuser('user', 'user@gallery',
                                                  'pass')
        self.client.login(username='******', password='******')

    def test_album_changelist(self):
        self.client.get(reverse('admin:gallery_album_changelist'))

    def test_photo_changelist(self):
        self.client.get(reverse('admin:gallery_photo_changelist'))

    def test_album_change(self):
        self.client.get(
            reverse('admin:gallery_album_change', args=[self.album.pk]))

    def test_photo_change(self):
        self.client.get(
            reverse('admin:gallery_photo_change', args=[self.photo.pk]))

    def test_scan_photos(self):
        self.client.get(reverse('admin:gallery_scan_photos'))
        tmpdir = tempfile.mkdtemp()
        with open(os.path.join(tmpdir, 'test'), 'wb') as handle:
            handle.write(b'test')
        try:
            with self.settings(GALLERY_PHOTO_DIR=tmpdir):
                self.client.post(reverse('admin:gallery_scan_photos'))
        finally:
            shutil.rmtree(tmpdir)

    def test_set_album_access_policy(self):
        response = self.client.post(
            reverse('admin:gallery_album_changelist'), {
                'action': 'set_access_policy',
                ACTION_CHECKBOX_NAME:
                [str(self.album.pk), str(self.album2.pk)],
            })
        self.assertTemplateUsed(response,
                                'admin/gallery/set_access_policy.html')
        self.assertFalse(
            Album.objects.get(pk=self.album.pk).access_policy.inherit)
        with self.assertRaises(AlbumAccessPolicy.DoesNotExist):
            Album.objects.get(pk=self.album2.pk).access_policy

        response = self.client.post(
            reverse('admin:gallery_album_changelist'), {
                'action': 'set_access_policy',
                ACTION_CHECKBOX_NAME:
                [str(self.album.pk), str(self.album2.pk)],
                'public': True,
                'inherit': True,
                'set_access_policy': "Set access policy",
            })
        self.assertRedirects(response,
                             reverse('admin:gallery_album_changelist'))
        self.assertTrue(
            Album.objects.get(pk=self.album.pk).access_policy.inherit)
        self.assertTrue(
            Album.objects.get(pk=self.album2.pk).access_policy.inherit)

    def test_set_album_access_policy_invalid_form(self):
        response = self.client.post(
            reverse('admin:gallery_album_changelist'), {
                'action': 'set_access_policy',
                ACTION_CHECKBOX_NAME:
                [str(self.album.pk), str(self.album2.pk)],
                'set_access_policy': "Set access policy",
                'users': ['-1'],
            })
        self.assertTemplateUsed(response,
                                'admin/gallery/set_access_policy.html')
        self.assertFormError(
            response, 'form', 'users',
            'Select a valid choice. -1 is not one of the available choices.')

    def test_set_album_access_policy_no_add_permission(self):
        self.user.is_superuser = False
        self.user.save()
        self.user.user_permissions.add(
            Permission.objects.get(codename='change_album'))

        response = self.client.post(
            reverse('admin:gallery_album_changelist'), {
                'action': 'set_access_policy',
                ACTION_CHECKBOX_NAME: [str(self.album2.pk)],
                'public': True,
                'inherit': True,
                'set_access_policy': "Set access policy",
            })
        self.assertEqual(response.status_code, 403)
        with self.assertRaises(AlbumAccessPolicy.DoesNotExist):
            Album.objects.get(pk=self.album2.pk).access_policy

    def test_set_album_access_policy_add_permission(self):
        self.user.is_superuser = False
        self.user.save()
        self.user.user_permissions.add(
            Permission.objects.get(codename='change_album'))
        self.user.user_permissions.add(
            Permission.objects.get(codename='add_albumaccesspolicy'))

        response = self.client.post(
            reverse('admin:gallery_album_changelist'), {
                'action': 'set_access_policy',
                ACTION_CHECKBOX_NAME: [str(self.album2.pk)],
                'public': True,
                'inherit': True,
                'set_access_policy': "Set access policy",
            })
        self.assertRedirects(response,
                             reverse('admin:gallery_album_changelist'))
        self.assertTrue(
            Album.objects.get(pk=self.album2.pk).access_policy.inherit)

    def test_set_album_access_policy_no_change_permission(self):
        self.user.is_superuser = False
        self.user.save()
        self.user.user_permissions.add(
            Permission.objects.get(codename='change_album'))

        response = self.client.post(
            reverse('admin:gallery_album_changelist'), {
                'action': 'set_access_policy',
                ACTION_CHECKBOX_NAME: [str(self.album.pk)],
                'public': True,
                'inherit': True,
                'set_access_policy': "Set access policy",
            })
        self.assertEqual(response.status_code, 403)
        self.assertFalse(
            Album.objects.get(pk=self.album.pk).access_policy.inherit)

    def test_set_album_access_policy_change_permission(self):
        self.user.is_superuser = False
        self.user.save()
        self.user.user_permissions.add(
            Permission.objects.get(codename='change_album'))
        self.user.user_permissions.add(
            Permission.objects.get(codename='change_albumaccesspolicy'))

        response = self.client.post(
            reverse('admin:gallery_album_changelist'), {
                'action': 'set_access_policy',
                ACTION_CHECKBOX_NAME: [str(self.album.pk)],
                'public': True,
                'inherit': True,
                'set_access_policy': "Set access policy",
            })
        self.assertRedirects(response,
                             reverse('admin:gallery_album_changelist'))
        self.assertTrue(
            Album.objects.get(pk=self.album.pk).access_policy.inherit)

    def test_unset_album_access_policy(self):
        response = self.client.post(
            reverse('admin:gallery_album_changelist'), {
                'action': 'unset_access_policy',
                ACTION_CHECKBOX_NAME:
                [str(self.album.pk), str(self.album2.pk)],
            })
        self.assertTemplateUsed(response,
                                'admin/gallery/unset_access_policy.html')
        self.assertTrue(
            Album.objects.get(pk=self.album.pk).access_policy.public)

        response = self.client.post(
            reverse('admin:gallery_album_changelist'), {
                'action': 'unset_access_policy',
                ACTION_CHECKBOX_NAME:
                [str(self.album.pk), str(self.album2.pk)],
                'public': True,
                'unset_access_policy': "Unset access policy",
            })
        self.assertRedirects(response,
                             reverse('admin:gallery_album_changelist'))
        with self.assertRaises(AlbumAccessPolicy.DoesNotExist):
            Album.objects.get(pk=self.album.pk).access_policy

    def test_unset_album_access_policy_no_delete_permission(self):
        self.user.is_superuser = False
        self.user.save()
        self.user.user_permissions.add(
            Permission.objects.get(codename='change_album'))

        response = self.client.post(
            reverse('admin:gallery_album_changelist'), {
                'action': 'unset_access_policy',
                ACTION_CHECKBOX_NAME: [str(self.album.pk)],
                'public': True,
                'unset_access_policy': "Unset access policy",
            })
        self.assertEqual(response.status_code, 403)
        self.assertTrue(
            Album.objects.get(pk=self.album.pk).access_policy.public)

    def test_unset_album_access_policy_delete_permission(self):
        self.user.is_superuser = False
        self.user.save()
        self.user.user_permissions.add(
            Permission.objects.get(codename='change_album'))
        self.user.user_permissions.add(
            Permission.objects.get(codename='delete_albumaccesspolicy'))

        response = self.client.post(
            reverse('admin:gallery_album_changelist'), {
                'action': 'unset_access_policy',
                ACTION_CHECKBOX_NAME: [str(self.album.pk)],
                'public': True,
                'unset_access_policy': "Unset access policy",
            })
        self.assertRedirects(response,
                             reverse('admin:gallery_album_changelist'))
        with self.assertRaises(AlbumAccessPolicy.DoesNotExist):
            Album.objects.get(pk=self.album.pk).access_policy

    # See https://code.djangoproject.com/ticket/24258
    if (3, 0) <= sys.version_info[:2] < (3, 3):  # pragma: no cover
        test_set_album_access_policy = unittest.expectedFailure(
            test_set_album_access_policy)
        test_set_album_access_policy_add_permission = unittest.expectedFailure(
            test_set_album_access_policy_add_permission)  # noqa
        test_set_album_access_policy_change_permission = unittest.expectedFailure(
            test_set_album_access_policy_change_permission)  # noqa
        test_unset_album_access_policy = unittest.expectedFailure(
            test_unset_album_access_policy)
        test_unset_album_access_policy_delete_permission = unittest.expectedFailure(
            test_unset_album_access_policy_delete_permission)  # noqa
Exemplo n.º 24
0
        ('TarSolidUnicode'        , 'test_list_contents'),
        ('TarSolidUnicode'        , 'test_iter_extract' ),
        ('TarSolidUnicode'        , 'test_extract'      ),
        # Idem with unzip...
        ('ZipExternalUnicode'     , 'test_iter_contents'),
        ('ZipExternalUnicode'     , 'test_list_contents'),
        ('ZipExternalUnicode'     , 'test_iter_extract' ),
        ('ZipExternalUnicode'     , 'test_extract'      ),
        # ...and unrar!
        ('RarExternalUnicode'     , 'test_iter_contents'),
        ('RarExternalUnicode'     , 'test_list_contents'),
        ('RarExternalUnicode'     , 'test_iter_extract' ),
        ('RarExternalUnicode'     , 'test_extract'      ),
        ('RarExternalSolidUnicode', 'test_iter_contents'),
        ('RarExternalSolidUnicode', 'test_list_contents'),
        ('RarExternalSolidUnicode', 'test_iter_extract' ),
        ('RarExternalSolidUnicode', 'test_extract'      ),
    ])

# Expected failures.
for test, attr in xfail_list:
    for name in (
        'ArchiveFormat%sTest' % test,
        'RecursiveArchiveFormat%sTest' % test,
    ):
        if not name in globals():
            continue
        klass = globals()[name]
        setattr(klass, attr, unittest.expectedFailure(getattr(klass, attr)))

Exemplo n.º 25
0
    for obj in serializers.deserialize(format, serialized_data):
        obj.save()

    # Assert that the deserialized data is the same
    # as the original source
    for (func, pk, klass, datum) in test_data:
        func[1](self, pk, klass, datum)

    # Assert that the number of objects deserialized is the
    # same as the number that was serialized.
    for klass, count in instance_count.items():
        self.assertEqual(count, klass.objects.count())

if connection.vendor == 'mysql' and six.PY3:
    # Existing MySQL DB-API drivers fail on binary data.
    serializerTest = expectedFailure(serializerTest)


def naturalKeySerializerTest(format, self):
    # Create all the objects defined in the test data
    objects = []
    instance_count = {}
    for (func, pk, klass, datum) in natural_key_test_data:
        with connection.constraint_checks_disabled():
            objects.extend(func[0](pk, klass, datum))

    # Get a count of the number of objects created for each class
    for klass in instance_count:
        instance_count[klass] = klass.objects.count()

    # use_natural_keys is deprecated and to be removed in Django 1.9
Exemplo n.º 26
0
class BroadcastTests(unittest.TestCase):
    def test_symbolic_shape(self):
        with self.assertWarns(UnsupportedBroadcastArgumentWarning):
            symbolic = Broadcast(a, (b, ))
        self.assertIs(symbolic.func, Broadcast)
        self.assertEqual(symbolic.args, (a, (b, )))

        subs_b = symbolic.subs({b: 6})
        self.assertIs(subs_b.func, Broadcast)
        self.assertEqual(subs_b.args, (a, (6, )))

        subs_a = symbolic.subs({a: 3})
        self.assertIs(subs_a.func, Broadcast)
        self.assertEqual(subs_a.args, (3, (b, )))

        subs_both_scalar = symbolic.subs({a: 3, b: 6})
        self.assertEqual(subs_both_scalar, sympy.Array([3, 3, 3, 3, 3, 3]))

        subs_both_array = symbolic.subs({a: (1, 2, 3, 4, 5, 6), b: 6})
        self.assertEqual(subs_both_array, sympy.Array([1, 2, 3, 4, 5, 6]))

        with self.assertRaises(ValueError):
            symbolic.subs({a: (1, 2, 3, 4, 5, 6), b: 7})

    def test_scalar_broad_cast(self):
        symbolic = Broadcast(a, (6, ))
        self.assertIs(symbolic.func, Broadcast)
        self.assertEqual(symbolic.args, (a, (6, )))

        subs_symbol = symbolic.subs({a: b})
        self.assertIs(subs_symbol.func, Broadcast)
        self.assertEqual(subs_symbol.args, (b, (6, )))

        subs_scalar = symbolic.subs({a: 3.4})
        self.assertEqual(subs_scalar,
                         sympy.Array([3.4, 3.4, 3.4, 3.4, 3.4, 3.4]))

        subs_symbol_vector = symbolic.subs({a: (b, 1, 2, 3, 4, 5)})
        self.assertEqual(subs_symbol_vector, sympy.Array([b, 1, 2, 3, 4, 5]))

        subs_numeric_vector = symbolic.subs({a: (0, 1, 2, 3, 4, 5)})
        self.assertEqual(subs_numeric_vector, sympy.Array([0, 1, 2, 3, 4, 5]))

        with self.assertRaises(ValueError):
            symbolic.subs({a: (b, 4, 5)})

        with self.assertRaises(ValueError):
            symbolic.subs({a: (8, 5, 3, 5, 5, 4, 4, 5)})

    def test_array_broadcast(self):
        expected = sympy.Array([1, 2, a, b])

        self.assertEqual(expected, Broadcast(list(expected), (4, )))
        self.assertEqual(expected, Broadcast(tuple(expected), (4, )))
        self.assertEqual(expected, Broadcast(expected, (4, )))

    def test_numeric_evaluation(self):
        with self.assertWarns(UnsupportedBroadcastArgumentWarning):
            # use c (and not b as above)
            # here because sympy caches function call results and we want the warning everytime
            symbolic = Broadcast(a, (c, ))

        arguments = {'a': (1, 2., 3), 'c': 3}
        expected = np.asarray([1, 2., 3])
        result, _ = evaluate_lambdified(symbolic, ['a', 'c'], arguments, None)
        np.testing.assert_array_equal(expected, result)

        with self.assertRaises(ValueError):
            arguments = {'a': (1, 2., 3), 'c': 4}
            evaluate_lambdified(symbolic, ['a', 'c'], arguments, None)

        arguments = {'a': 1, 'c': 3}
        expected = np.asarray([1, 1, 1])
        result, _ = evaluate_lambdified(symbolic, ['a', 'c'], arguments, None)
        np.testing.assert_array_equal(expected, result)

    def test_sympification(self):
        symbolic = Broadcast(a, (3, ))
        as_str = str(symbolic)

        re_sympified = qc_sympify(as_str)
        self.assertEqual(re_sympified, symbolic)

        sympification = qc_sympify('Broadcast(a, (3,))')
        self.assertEqual(sympification, symbolic)

    def test_expression_equality(self):
        """Sympy decided to change their equality reasoning"""
        self.assertEqual(sympy.sympify('3'), sympy.sympify('3.'))
        self.assertEqual(sympy.sympify('3 + a'), sympy.sympify('3 + a'))
        self.assertEqual(sympy.sympify('3 + a'), sympy.sympify('3. + a'))

        expr_with_float = sympy.sympify('a*(b - 3.0) + (-b + c)*(d + 4.0)/2')
        expr_with_int = sympy.sympify('a*(b - 3) + (-b + c)*(d + 4)/2')
        expr_with_int_other_order = sympy.sympify('(b-3)*a + (c-b)*(d+4) / 2')

        self.assertEqual(expr_with_float, expr_with_int)
        self.assertEqual(expr_with_int, expr_with_int_other_order)
        self.assertEqual(expr_with_float, expr_with_int_other_order)

    test_numeric_equal = unittest.expectedFailure(
        test_expression_equality) if Version(
            sympy.__version__) >= Version('1.5') else test_expression_equality

    def test_integral(self):
        symbolic = Broadcast(a * c, (3, ))
        indexed = symbolic[1]

        integ = sympy.Integral(symbolic, (a, 0, b))
        idx_integ = sympy.Integral(indexed, (a, 0, b))
        self.assertEqual(integ,
                         Broadcast(sympy.Integral(a * c, (a, 0, b)), (3, )))
        self.assertEqual(idx_integ,
                         Broadcast(sympy.Integral(a * c, (a, 0, b)), (3, ))[1])

        diffed = sympy.diff(symbolic, a)
        idx_diffed = sympy.diff(indexed, a)
        self.assertEqual(symbolic.subs(a, 1), diffed)
        self.assertEqual(indexed.subs(a, 1), idx_diffed)

    def test_indexing(self):
        symbolic = Broadcast(a, (3, ))
        indexed = symbolic[1]

        self.assertEqual(7, indexed.subs(a, 7))
        self.assertEqual(7, indexed.subs(a, (6, 7, 8)))
Exemplo n.º 27
0
class CaseExpressionTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        o = CaseTestModel.objects.create(integer=1, integer2=1, string='1')
        O2OCaseTestModel.objects.create(o2o=o, integer=1)
        FKCaseTestModel.objects.create(fk=o, integer=1)

        o = CaseTestModel.objects.create(integer=2, integer2=3, string='2')
        O2OCaseTestModel.objects.create(o2o=o, integer=2)
        FKCaseTestModel.objects.create(fk=o, integer=2)
        FKCaseTestModel.objects.create(fk=o, integer=3)

        o = CaseTestModel.objects.create(integer=3, integer2=4, string='3')
        O2OCaseTestModel.objects.create(o2o=o, integer=3)
        FKCaseTestModel.objects.create(fk=o, integer=3)
        FKCaseTestModel.objects.create(fk=o, integer=4)

        o = CaseTestModel.objects.create(integer=2, integer2=2, string='2')
        O2OCaseTestModel.objects.create(o2o=o, integer=2)
        FKCaseTestModel.objects.create(fk=o, integer=2)
        FKCaseTestModel.objects.create(fk=o, integer=3)

        o = CaseTestModel.objects.create(integer=3, integer2=4, string='3')
        O2OCaseTestModel.objects.create(o2o=o, integer=3)
        FKCaseTestModel.objects.create(fk=o, integer=3)
        FKCaseTestModel.objects.create(fk=o, integer=4)

        o = CaseTestModel.objects.create(integer=3, integer2=3, string='3')
        O2OCaseTestModel.objects.create(o2o=o, integer=3)
        FKCaseTestModel.objects.create(fk=o, integer=3)
        FKCaseTestModel.objects.create(fk=o, integer=4)

        o = CaseTestModel.objects.create(integer=4, integer2=5, string='4')
        O2OCaseTestModel.objects.create(o2o=o, integer=1)
        FKCaseTestModel.objects.create(fk=o, integer=5)

        # GROUP BY on Oracle fails with TextField/BinaryField; see #24096.
        cls.non_lob_fields = [
            f.name for f in CaseTestModel._meta.get_fields()
            if not (f.is_relation and f.auto_created)
            and not isinstance(f, (models.BinaryField, models.TextField))
        ]

    def test_annotate(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(test=Case(
            When(integer=1, then=Value('one')),
            When(integer=2, then=Value('two')),
            default=Value('other'),
            output_field=models.CharField(),
        )).order_by('pk'), [(1, 'one'), (2, 'two'), (3, 'other'), (2, 'two'),
                            (3, 'other'), (3, 'other'), (4, 'other')],
                                 transform=attrgetter('integer', 'test'))

    def test_annotate_without_default(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(test=Case(
            When(integer=1, then=1),
            When(integer=2, then=2),
            output_field=models.IntegerField(),
        )).order_by('pk'), [(1, 1), (2, 2), (3, None), (2, 2), (3, None),
                            (3, None), (4, None)],
                                 transform=attrgetter('integer', 'test'))

    def test_annotate_with_expression_as_value(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(f_test=Case(
            When(integer=1, then=F('integer') + 1),
            When(integer=2, then=F('integer') + 3),
            default='integer',
        )).order_by('pk'), [(1, 2), (2, 5), (3, 3), (2, 5), (3, 3), (3, 3),
                            (4, 4)],
                                 transform=attrgetter('integer', 'f_test'))

    def test_annotate_with_expression_as_condition(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(f_test=Case(
            When(integer2=F('integer'), then=Value('equal')),
            When(integer2=F('integer') + 1, then=Value('+1')),
            output_field=models.CharField(),
        )).order_by('pk'), [(1, 'equal'), (2, '+1'), (3, '+1'), (2, 'equal'),
                            (3, '+1'), (3, 'equal'), (4, '+1')],
                                 transform=attrgetter('integer', 'f_test'))

    def test_annotate_with_join_in_value(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(join_test=Case(
            When(integer=1, then=F('o2o_rel__integer') + 1),
            When(integer=2, then=F('o2o_rel__integer') + 3),
            default='o2o_rel__integer',
        )).order_by('pk'), [(1, 2), (2, 5), (3, 3), (2, 5), (3, 3), (3, 3),
                            (4, 1)],
                                 transform=attrgetter('integer', 'join_test'))

    def test_annotate_with_join_in_condition(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(join_test=Case(
            When(integer2=F('o2o_rel__integer'), then=Value('equal')),
            When(integer2=F('o2o_rel__integer') + 1, then=Value('+1')),
            default=Value('other'),
            output_field=models.CharField(),
        )).order_by('pk'), [(1, 'equal'), (2, '+1'), (3, '+1'), (2, 'equal'),
                            (3, '+1'), (3, 'equal'), (4, 'other')],
                                 transform=attrgetter('integer', 'join_test'))

    def test_annotate_with_join_in_predicate(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(join_test=Case(
            When(o2o_rel__integer=1, then=Value('one')),
            When(o2o_rel__integer=2, then=Value('two')),
            When(o2o_rel__integer=3, then=Value('three')),
            default=Value('other'),
            output_field=models.CharField(),
        )).order_by('pk'), [(1, 'one'), (2, 'two'), (3, 'three'), (2, 'two'),
                            (3, 'three'), (3, 'three'), (4, 'one')],
                                 transform=attrgetter('integer', 'join_test'))

    def test_annotate_with_annotation_in_value(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(
            f_plus_1=F('integer') + 1,
            f_plus_3=F('integer') + 3,
        ).annotate(f_test=Case(
            When(integer=1, then='f_plus_1'),
            When(integer=2, then='f_plus_3'),
            default='integer',
        ), ).order_by('pk'), [(1, 2), (2, 5), (3, 3), (2, 5), (3, 3), (3, 3),
                              (4, 4)],
                                 transform=attrgetter('integer', 'f_test'))

    def test_annotate_with_annotation_in_condition(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(
            f_plus_1=F('integer') + 1, ).annotate(f_test=Case(
                When(integer2=F('integer'), then=Value('equal')),
                When(integer2=F('f_plus_1'), then=Value('+1')),
                output_field=models.CharField(),
            ), ).order_by('pk'), [(1, 'equal'), (2, '+1'), (3, '+1'),
                                  (2, 'equal'), (3, '+1'), (3, 'equal'),
                                  (4, '+1')],
                                 transform=attrgetter('integer', 'f_test'))

    def test_annotate_with_annotation_in_predicate(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(
            f_minus_2=F('integer') - 2, ).annotate(test=Case(
                When(f_minus_2=-1, then=Value('negative one')),
                When(f_minus_2=0, then=Value('zero')),
                When(f_minus_2=1, then=Value('one')),
                default=Value('other'),
                output_field=models.CharField(),
            ), ).order_by('pk'), [(1, 'negative one'), (2, 'zero'), (3, 'one'),
                                  (2, 'zero'), (3, 'one'), (3, 'one'),
                                  (4, 'other')],
                                 transform=attrgetter('integer', 'test'))

    def test_annotate_with_aggregation_in_value(self):
        self.assertQuerysetEqual(
            CaseTestModel.objects.values(*self.non_lob_fields).annotate(
                min=Min('fk_rel__integer'),
                max=Max('fk_rel__integer'),
            ).annotate(test=Case(
                When(integer=2, then='min'),
                When(integer=3, then='max'),
            ), ).order_by('pk'), [(1, None, 1, 1), (2, 2, 2, 3), (3, 4, 3, 4),
                                  (2, 2, 2, 3), (3, 4, 3, 4), (3, 4, 3, 4),
                                  (4, None, 5, 5)],
            transform=itemgetter('integer', 'test', 'min', 'max'))

    def test_annotate_with_aggregation_in_condition(self):
        self.assertQuerysetEqual(
            CaseTestModel.objects.values(*self.non_lob_fields).annotate(
                min=Min('fk_rel__integer'),
                max=Max('fk_rel__integer'),
            ).annotate(test=Case(
                When(integer2=F('min'), then=Value('min')),
                When(integer2=F('max'), then=Value('max')),
                output_field=models.CharField(),
            ), ).order_by('pk'), [(1, 1, 'min'), (2, 3, 'max'), (3, 4, 'max'),
                                  (2, 2, 'min'), (3, 4, 'max'), (3, 3, 'min'),
                                  (4, 5, 'min')],
            transform=itemgetter('integer', 'integer2', 'test'))

    def test_annotate_with_aggregation_in_predicate(self):
        self.assertQuerysetEqual(
            CaseTestModel.objects.values(*self.non_lob_fields).annotate(
                max=Max('fk_rel__integer'), ).annotate(test=Case(
                    When(max=3, then=Value('max = 3')),
                    When(max=4, then=Value('max = 4')),
                    default=Value(''),
                    output_field=models.CharField(),
                ), ).order_by('pk'), [(1, 1, ''), (2, 3, 'max = 3'),
                                      (3, 4, 'max = 4'), (2, 3, 'max = 3'),
                                      (3, 4, 'max = 4'), (3, 4, 'max = 4'),
                                      (4, 5, '')],
            transform=itemgetter('integer', 'max', 'test'))

    def test_combined_expression(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(test=Case(
            When(integer=1, then=2),
            When(integer=2, then=1),
            default=3,
            output_field=models.IntegerField(),
        ) + 1, ).order_by('pk'), [(1, 3), (2, 2), (3, 4), (2, 2), (3, 4),
                                  (3, 4), (4, 4)],
                                 transform=attrgetter('integer', 'test'))

    if connection.vendor == 'sqlite' and connection.Database.sqlite_version_info < (
            3, 7, 0):
        # There is a bug in sqlite < 3.7.0, where placeholder order is lost.
        # Thus, the above query returns  <condition_value> + <result_value>
        # for each matching case instead of <result_value> + 1 (#24148).
        test_combined_expression = unittest.expectedFailure(
            test_combined_expression)

    def test_in_subquery(self):
        self.assertQuerysetEqual(CaseTestModel.objects.filter(
            pk__in=CaseTestModel.objects.annotate(test=Case(
                When(integer=F('integer2'), then='pk'),
                When(integer=4, then='pk'),
                output_field=models.IntegerField(),
            ), ).values('test')).order_by('pk'), [(1, 1), (2, 2), (3, 3),
                                                  (4, 5)],
                                 transform=attrgetter('integer', 'integer2'))

    def test_case_reuse(self):
        SOME_CASE = Case(
            When(pk=0, then=Value('0')),
            default=Value('1'),
            output_field=models.CharField(),
        )
        self.assertQuerysetEqual(
            CaseTestModel.objects.annotate(somecase=SOME_CASE).order_by('pk'),
            CaseTestModel.objects.annotate(
                somecase=SOME_CASE).order_by('pk').values_list(
                    'pk', 'somecase'), lambda x: (x.pk, x.somecase))

    def test_aggregate(self):
        self.assertEqual(
            CaseTestModel.objects.aggregate(
                one=models.Sum(
                    Case(
                        When(integer=1, then=1),
                        output_field=models.IntegerField(),
                    )),
                two=models.Sum(
                    Case(
                        When(integer=2, then=1),
                        output_field=models.IntegerField(),
                    )),
                three=models.Sum(
                    Case(
                        When(integer=3, then=1),
                        output_field=models.IntegerField(),
                    )),
                four=models.Sum(
                    Case(
                        When(integer=4, then=1),
                        output_field=models.IntegerField(),
                    )),
            ), {
                'one': 1,
                'two': 2,
                'three': 3,
                'four': 1
            })

    def test_aggregate_with_expression_as_value(self):
        self.assertEqual(
            CaseTestModel.objects.aggregate(
                one=models.Sum(Case(When(integer=1, then='integer'))),
                two=models.Sum(Case(When(integer=2, then=F('integer') - 1))),
                three=models.Sum(Case(When(integer=3, then=F('integer') + 1))),
            ), {
                'one': 1,
                'two': 2,
                'three': 12
            })

    def test_aggregate_with_expression_as_condition(self):
        self.assertEqual(
            CaseTestModel.objects.aggregate(
                equal=models.Sum(
                    Case(
                        When(integer2=F('integer'), then=1),
                        output_field=models.IntegerField(),
                    )),
                plus_one=models.Sum(
                    Case(
                        When(integer2=F('integer') + 1, then=1),
                        output_field=models.IntegerField(),
                    )),
            ), {
                'equal': 3,
                'plus_one': 4
            })

    def test_filter(self):
        self.assertQuerysetEqual(CaseTestModel.objects.filter(integer2=Case(
            When(integer=2, then=3),
            When(integer=3, then=4),
            default=1,
            output_field=models.IntegerField(),
        )).order_by('pk'), [(1, 1), (2, 3), (3, 4), (3, 4)],
                                 transform=attrgetter('integer', 'integer2'))

    def test_filter_without_default(self):
        self.assertQuerysetEqual(CaseTestModel.objects.filter(integer2=Case(
            When(integer=2, then=3),
            When(integer=3, then=4),
            output_field=models.IntegerField(),
        )).order_by('pk'), [(2, 3), (3, 4), (3, 4)],
                                 transform=attrgetter('integer', 'integer2'))

    def test_filter_with_expression_as_value(self):
        self.assertQuerysetEqual(CaseTestModel.objects.filter(integer2=Case(
            When(integer=2, then=F('integer') + 1),
            When(integer=3, then=F('integer')),
            default='integer',
        )).order_by('pk'), [(1, 1), (2, 3), (3, 3)],
                                 transform=attrgetter('integer', 'integer2'))

    def test_filter_with_expression_as_condition(self):
        self.assertQuerysetEqual(CaseTestModel.objects.filter(string=Case(
            When(integer2=F('integer'), then=Value('2')),
            When(integer2=F('integer') + 1, then=Value('3')),
            output_field=models.CharField(),
        )).order_by('pk'), [(3, 4, '3'), (2, 2, '2'), (3, 4, '3')],
                                 transform=attrgetter('integer', 'integer2',
                                                      'string'))

    def test_filter_with_join_in_value(self):
        self.assertQuerysetEqual(CaseTestModel.objects.filter(integer2=Case(
            When(integer=2, then=F('o2o_rel__integer') + 1),
            When(integer=3, then=F('o2o_rel__integer')),
            default='o2o_rel__integer',
        )).order_by('pk'), [(1, 1), (2, 3), (3, 3)],
                                 transform=attrgetter('integer', 'integer2'))

    def test_filter_with_join_in_condition(self):
        self.assertQuerysetEqual(CaseTestModel.objects.filter(integer=Case(
            When(integer2=F('o2o_rel__integer') + 1, then=2),
            When(integer2=F('o2o_rel__integer'), then=3),
            output_field=models.IntegerField(),
        )).order_by('pk'), [(2, 3), (3, 3)],
                                 transform=attrgetter('integer', 'integer2'))

    def test_filter_with_join_in_predicate(self):
        self.assertQuerysetEqual(CaseTestModel.objects.filter(integer2=Case(
            When(o2o_rel__integer=1, then=1),
            When(o2o_rel__integer=2, then=3),
            When(o2o_rel__integer=3, then=4),
            output_field=models.IntegerField(),
        )).order_by('pk'), [(1, 1), (2, 3), (3, 4), (3, 4)],
                                 transform=attrgetter('integer', 'integer2'))

    def test_filter_with_annotation_in_value(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(
            f=F('integer'),
            f_plus_1=F('integer') + 1,
        ).filter(integer2=Case(
            When(integer=2, then='f_plus_1'),
            When(integer=3, then='f'),
        ), ).order_by('pk'), [(2, 3), (3, 3)],
                                 transform=attrgetter('integer', 'integer2'))

    def test_filter_with_annotation_in_condition(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(
            f_plus_1=F('integer') + 1, ).filter(integer=Case(
                When(integer2=F('integer'), then=2),
                When(integer2=F('f_plus_1'), then=3),
                output_field=models.IntegerField(),
            ), ).order_by('pk'), [(3, 4), (2, 2), (3, 4)],
                                 transform=attrgetter('integer', 'integer2'))

    def test_filter_with_annotation_in_predicate(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(
            f_plus_1=F('integer') + 1, ).filter(integer2=Case(
                When(f_plus_1=3, then=3),
                When(f_plus_1=4, then=4),
                default=1,
                output_field=models.IntegerField(),
            ), ).order_by('pk'), [(1, 1), (2, 3), (3, 4), (3, 4)],
                                 transform=attrgetter('integer', 'integer2'))

    def test_filter_with_aggregation_in_value(self):
        self.assertQuerysetEqual(
            CaseTestModel.objects.values(*self.non_lob_fields).annotate(
                min=Min('fk_rel__integer'),
                max=Max('fk_rel__integer'),
            ).filter(integer2=Case(
                When(integer=2, then='min'),
                When(integer=3, then='max'),
            ), ).order_by('pk'), [(3, 4, 3, 4), (2, 2, 2, 3), (3, 4, 3, 4)],
            transform=itemgetter('integer', 'integer2', 'min', 'max'))

    def test_filter_with_aggregation_in_condition(self):
        self.assertQuerysetEqual(
            CaseTestModel.objects.values(*self.non_lob_fields).annotate(
                min=Min('fk_rel__integer'),
                max=Max('fk_rel__integer'),
            ).filter(integer=Case(
                When(integer2=F('min'), then=2),
                When(integer2=F('max'), then=3),
            ), ).order_by('pk'), [(3, 4, 3, 4), (2, 2, 2, 3), (3, 4, 3, 4)],
            transform=itemgetter('integer', 'integer2', 'min', 'max'))

    def test_filter_with_aggregation_in_predicate(self):
        self.assertQuerysetEqual(
            CaseTestModel.objects.values(*self.non_lob_fields).annotate(
                max=Max('fk_rel__integer'), ).filter(integer=Case(
                    When(max=3, then=2),
                    When(max=4, then=3),
                ), ).order_by('pk'), [(2, 3, 3), (3, 4, 4), (2, 2, 3),
                                      (3, 4, 4), (3, 3, 4)],
            transform=itemgetter('integer', 'integer2', 'max'))

    def test_update(self):
        CaseTestModel.objects.update(string=Case(
            When(integer=1, then=Value('one')),
            When(integer=2, then=Value('two')),
            default=Value('other'),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, 'one'), (2, 'two'), (3, 'other'),
                                  (2, 'two'), (3, 'other'), (3, 'other'),
                                  (4, 'other')],
                                 transform=attrgetter('integer', 'string'))

    def test_update_without_default(self):
        CaseTestModel.objects.update(integer2=Case(
            When(integer=1, then=1),
            When(integer=2, then=2),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, 1), (2, 2), (3, None), (2, 2), (3, None),
                                  (3, None), (4, None)],
                                 transform=attrgetter('integer', 'integer2'))

    def test_update_with_expression_as_value(self):
        CaseTestModel.objects.update(integer=Case(
            When(integer=1, then=F('integer') + 1),
            When(integer=2, then=F('integer') + 3),
            default='integer',
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [('1', 2), ('2', 5), ('3', 3), ('2', 5),
                                  ('3', 3), ('3', 3), ('4', 4)],
                                 transform=attrgetter('string', 'integer'))

    def test_update_with_expression_as_condition(self):
        CaseTestModel.objects.update(string=Case(
            When(integer2=F('integer'), then=Value('equal')),
            When(integer2=F('integer') + 1, then=Value('+1')),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, 'equal'), (2, '+1'), (3, '+1'),
                                  (2, 'equal'), (3, '+1'), (3, 'equal'),
                                  (4, '+1')],
                                 transform=attrgetter('integer', 'string'))

    def test_update_with_join_in_condition_raise_field_error(self):
        with self.assertRaisesMessage(
                FieldError,
                'Joined field references are not permitted in this query'):
            CaseTestModel.objects.update(integer=Case(
                When(integer2=F('o2o_rel__integer') + 1, then=2),
                When(integer2=F('o2o_rel__integer'), then=3),
                output_field=models.IntegerField(),
            ), )

    def test_update_with_join_in_predicate_raise_field_error(self):
        with self.assertRaisesMessage(
                FieldError,
                'Joined field references are not permitted in this query'):
            CaseTestModel.objects.update(string=Case(
                When(o2o_rel__integer=1, then=Value('one')),
                When(o2o_rel__integer=2, then=Value('two')),
                When(o2o_rel__integer=3, then=Value('three')),
                default=Value('other'),
                output_field=models.CharField(),
            ), )

    def test_update_big_integer(self):
        CaseTestModel.objects.update(big_integer=Case(
            When(integer=1, then=1),
            When(integer=2, then=2),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, 1), (2, 2), (3, None), (2, 2), (3, None),
                                  (3, None), (4, None)],
                                 transform=attrgetter('integer',
                                                      'big_integer'))

    def test_update_binary(self):
        CaseTestModel.objects.update(
            binary=Case(
                # fails on postgresql on Python 2.7 if output_field is not
                # set explicitly
                When(integer=1,
                     then=Value(b'one', output_field=models.BinaryField())),
                When(integer=2,
                     then=Value(b'two', output_field=models.BinaryField())),
                default=Value(b'', output_field=models.BinaryField()),
            ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, b'one'), (2, b'two'), (3, b''),
                                  (2, b'two'), (3, b''), (3, b''), (4, b'')],
                                 transform=lambda o:
                                 (o.integer, six.binary_type(o.binary)))

    def test_update_boolean(self):
        CaseTestModel.objects.update(boolean=Case(
            When(integer=1, then=True),
            When(integer=2, then=True),
            default=False,
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, True), (2, True), (3, False), (2, True),
                                  (3, False), (3, False), (4, False)],
                                 transform=attrgetter('integer', 'boolean'))

    def test_update_comma_separated_integer(self):
        CaseTestModel.objects.update(comma_separated_integer=Case(
            When(integer=1, then=Value('1')),
            When(integer=2, then=Value('2,2')),
            default=Value(''),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, '1'), (2, '2,2'), (3, ''), (2, '2,2'),
                                  (3, ''), (3, ''), (4, '')],
                                 transform=attrgetter(
                                     'integer', 'comma_separated_integer'))

    def test_update_date(self):
        CaseTestModel.objects.update(date=Case(
            When(integer=1, then=date(2015, 1, 1)),
            When(integer=2, then=date(2015, 1, 2)),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, date(2015, 1, 1)), (2, date(2015, 1, 2)),
                                  (3, None), (2, date(2015, 1, 2)), (3, None),
                                  (3, None), (4, None)],
                                 transform=attrgetter('integer', 'date'))

    def test_update_date_time(self):
        CaseTestModel.objects.update(date_time=Case(
            When(integer=1, then=datetime(2015, 1, 1)),
            When(integer=2, then=datetime(2015, 1, 2)),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, datetime(2015, 1, 1)),
                                  (2, datetime(2015, 1, 2)), (3, None),
                                  (2, datetime(2015, 1, 2)), (3, None),
                                  (3, None), (4, None)],
                                 transform=attrgetter('integer', 'date_time'))

    def test_update_decimal(self):
        CaseTestModel.objects.update(decimal=Case(
            When(integer=1, then=Decimal('1.1')),
            When(integer=2, then=Decimal('2.2')),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, Decimal('1.1')), (2, Decimal('2.2')),
                                  (3, None), (2, Decimal('2.2')), (3, None),
                                  (3, None), (4, None)],
                                 transform=attrgetter('integer', 'decimal'))

    def test_update_duration(self):
        CaseTestModel.objects.update(
            duration=Case(
                # fails on sqlite if output_field is not set explicitly on all
                # Values containing timedeltas
                When(integer=1,
                     then=Value(timedelta(1),
                                output_field=models.DurationField())),
                When(integer=2,
                     then=Value(timedelta(2),
                                output_field=models.DurationField())),
            ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, timedelta(1)), (2, timedelta(2)),
                                  (3, None), (2, timedelta(2)), (3, None),
                                  (3, None), (4, None)],
                                 transform=attrgetter('integer', 'duration'))

    def test_update_email(self):
        CaseTestModel.objects.update(email=Case(
            When(integer=1, then=Value('*****@*****.**')),
            When(integer=2, then=Value('*****@*****.**')),
            default=Value(''),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, '*****@*****.**'), (2, '*****@*****.**'),
                                  (3, ''), (2, '*****@*****.**'), (3, ''),
                                  (3, ''), (4, '')],
                                 transform=attrgetter('integer', 'email'))

    def test_update_file(self):
        CaseTestModel.objects.update(file=Case(
            When(integer=1, then=Value('~/1')),
            When(integer=2, then=Value('~/2')),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, '~/1'), (2, '~/2'), (3, ''), (2, '~/2'),
                                  (3, ''), (3, ''), (4, '')],
                                 transform=lambda o:
                                 (o.integer, six.text_type(o.file)))

    def test_update_file_path(self):
        CaseTestModel.objects.update(file_path=Case(
            When(integer=1, then=Value('~/1')),
            When(integer=2, then=Value('~/2')),
            default=Value(''),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, '~/1'), (2, '~/2'), (3, ''), (2, '~/2'),
                                  (3, ''), (3, ''), (4, '')],
                                 transform=attrgetter('integer', 'file_path'))

    def test_update_float(self):
        CaseTestModel.objects.update(float=Case(
            When(integer=1, then=1.1),
            When(integer=2, then=2.2),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, 1.1), (2, 2.2), (3, None), (2, 2.2),
                                  (3, None), (3, None), (4, None)],
                                 transform=attrgetter('integer', 'float'))

    @unittest.skipUnless(Image, "Pillow not installed")
    def test_update_image(self):
        CaseTestModel.objects.update(image=Case(
            When(integer=1, then=Value('~/1')),
            When(integer=2, then=Value('~/2')),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, '~/1'), (2, '~/2'), (3, ''), (2, '~/2'),
                                  (3, ''), (3, ''), (4, '')],
                                 transform=lambda o:
                                 (o.integer, six.text_type(o.image)))

    def test_update_generic_ip_address(self):
        CaseTestModel.objects.update(
            generic_ip_address=Case(
                # fails on postgresql if output_field is not set explicitly
                When(integer=1, then=Value('1.1.1.1')),
                When(integer=2, then=Value('2.2.2.2')),
                output_field=models.GenericIPAddressField(),
            ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, '1.1.1.1'), (2, '2.2.2.2'), (3, None),
                                  (2, '2.2.2.2'), (3, None), (3, None),
                                  (4, None)],
                                 transform=attrgetter('integer',
                                                      'generic_ip_address'))

    def test_update_null_boolean(self):
        CaseTestModel.objects.update(null_boolean=Case(
            When(integer=1, then=True),
            When(integer=2, then=False),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, True), (2, False), (3, None), (2, False),
                                  (3, None), (3, None), (4, None)],
                                 transform=attrgetter('integer',
                                                      'null_boolean'))

    def test_update_positive_integer(self):
        CaseTestModel.objects.update(positive_integer=Case(
            When(integer=1, then=1),
            When(integer=2, then=2),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, 1), (2, 2), (3, None), (2, 2), (3, None),
                                  (3, None), (4, None)],
                                 transform=attrgetter('integer',
                                                      'positive_integer'))

    def test_update_positive_small_integer(self):
        CaseTestModel.objects.update(positive_small_integer=Case(
            When(integer=1, then=1),
            When(integer=2, then=2),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, 1), (2, 2), (3, None), (2, 2), (3, None),
                                  (3, None), (4, None)],
                                 transform=attrgetter(
                                     'integer', 'positive_small_integer'))

    def test_update_slug(self):
        CaseTestModel.objects.update(slug=Case(
            When(integer=1, then=Value('1')),
            When(integer=2, then=Value('2')),
            default=Value(''),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, '1'), (2, '2'), (3, ''), (2, '2'),
                                  (3, ''), (3, ''), (4, '')],
                                 transform=attrgetter('integer', 'slug'))

    def test_update_small_integer(self):
        CaseTestModel.objects.update(small_integer=Case(
            When(integer=1, then=1),
            When(integer=2, then=2),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, 1), (2, 2), (3, None), (2, 2), (3, None),
                                  (3, None), (4, None)],
                                 transform=attrgetter('integer',
                                                      'small_integer'))

    def test_update_string(self):
        CaseTestModel.objects.filter(string__in=['1', '2']).update(string=Case(
            When(integer=1, then=Value('1', output_field=models.CharField())),
            When(integer=2, then=Value('2', output_field=models.CharField())),
        ), )
        self.assertQuerysetEqual(
            CaseTestModel.objects.filter(string__in=['1', '2']).order_by('pk'),
            [(1, '1'), (2, '2'), (2, '2')],
            transform=attrgetter('integer', 'string'))

    def test_update_text(self):
        CaseTestModel.objects.update(text=Case(
            When(integer=1, then=Value('1')),
            When(integer=2, then=Value('2')),
            default=Value(''),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, '1'), (2, '2'), (3, ''), (2, '2'),
                                  (3, ''), (3, ''), (4, '')],
                                 transform=attrgetter('integer', 'text'))

    def test_update_time(self):
        CaseTestModel.objects.update(
            time=Case(
                # fails on sqlite if output_field is not set explicitly on all
                # Values containing times
                When(integer=1,
                     then=Value(time(1), output_field=models.TimeField())),
                When(integer=2,
                     then=Value(time(2), output_field=models.TimeField())),
            ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, time(1)), (2, time(2)), (3, None),
                                  (2, time(2)), (3, None), (3, None),
                                  (4, None)],
                                 transform=attrgetter('integer', 'time'))

    def test_update_url(self):
        CaseTestModel.objects.update(url=Case(
            When(integer=1, then=Value('http://1.example.com/')),
            When(integer=2, then=Value('http://2.example.com/')),
            default=Value(''),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, 'http://1.example.com/'),
                                  (2, 'http://2.example.com/'), (3, ''),
                                  (2, 'http://2.example.com/'), (3, ''),
                                  (3, ''), (4, '')],
                                 transform=attrgetter('integer', 'url'))

    def test_update_uuid(self):
        CaseTestModel.objects.update(
            uuid=Case(
                # fails on sqlite if output_field is not set explicitly on all
                # Values containing UUIDs
                When(integer=1,
                     then=Value(
                         UUID('11111111111111111111111111111111'),
                         output_field=models.UUIDField(),
                     )),
                When(integer=2,
                     then=Value(
                         UUID('22222222222222222222222222222222'),
                         output_field=models.UUIDField(),
                     )),
            ), )
        self.assertQuerysetEqual(
            CaseTestModel.objects.all().order_by('pk'),
            [(1, UUID('11111111111111111111111111111111')),
             (2, UUID('22222222222222222222222222222222')), (3, None),
             (2, UUID('22222222222222222222222222222222')), (3, None),
             (3, None), (4, None)],
            transform=attrgetter('integer', 'uuid'))

    def test_update_fk(self):
        obj1, obj2 = CaseTestModel.objects.all()[:2]

        CaseTestModel.objects.update(fk=Case(
            When(integer=1, then=obj1.pk),
            When(integer=2, then=obj2.pk),
        ), )
        self.assertQuerysetEqual(CaseTestModel.objects.all().order_by('pk'),
                                 [(1, obj1.pk), (2, obj2.pk), (3, None),
                                  (2, obj2.pk), (3, None), (3, None),
                                  (4, None)],
                                 transform=attrgetter('integer', 'fk_id'))

    def test_lookup_in_condition(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(test=Case(
            When(integer__lt=2, then=Value('less than 2')),
            When(integer__gt=2, then=Value('greater than 2')),
            default=Value('equal to 2'),
            output_field=models.CharField(),
        ), ).order_by('pk'), [(1, 'less than 2'), (2, 'equal to 2'),
                              (3, 'greater than 2'), (2, 'equal to 2'),
                              (3, 'greater than 2'), (3, 'greater than 2'),
                              (4, 'greater than 2')],
                                 transform=attrgetter('integer', 'test'))

    def test_lookup_different_fields(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(test=Case(
            When(integer=2, integer2=3, then=Value('when')),
            default=Value('default'),
            output_field=models.CharField(),
        ), ).order_by('pk'), [(1, 1, 'default'), (2, 3, 'when'),
                              (3, 4, 'default'), (2, 2, 'default'),
                              (3, 4, 'default'), (3, 3, 'default'),
                              (4, 5, 'default')],
                                 transform=attrgetter('integer', 'integer2',
                                                      'test'))

    def test_combined_q_object(self):
        self.assertQuerysetEqual(CaseTestModel.objects.annotate(test=Case(
            When(Q(integer=2) | Q(integer2=3), then=Value('when')),
            default=Value('default'),
            output_field=models.CharField(),
        ), ).order_by('pk'), [(1, 1, 'default'), (2, 3, 'when'),
                              (3, 4, 'default'), (2, 2, 'when'),
                              (3, 4, 'default'), (3, 3, 'when'),
                              (4, 5, 'default')],
                                 transform=attrgetter('integer', 'integer2',
                                                      'test'))

    def test_order_by_conditional_implicit(self):
        self.assertQuerysetEqual(
            CaseTestModel.objects.filter(integer__lte=2).annotate(test=Case(
                When(integer=1, then=2),
                When(integer=2, then=1),
                default=3,
                output_field=models.IntegerField(),
            )).order_by('test', 'pk'), [(2, 1), (2, 1), (1, 2)],
            transform=attrgetter('integer', 'test'))

    def test_order_by_conditional_explicit(self):
        self.assertQuerysetEqual(
            CaseTestModel.objects.filter(integer__lte=2).annotate(test=Case(
                When(integer=1, then=2),
                When(integer=2, then=1),
                default=3,
                output_field=models.IntegerField(),
            )).order_by(F('test').asc(), 'pk'), [(2, 1), (2, 1), (1, 2)],
            transform=attrgetter('integer', 'test'))

    def test_join_promotion(self):
        o = CaseTestModel.objects.create(integer=1, integer2=1, string='1')
        # Testing that:
        # 1. There isn't any object on the remote side of the fk_rel
        #    relation. If the query used inner joins, then the join to fk_rel
        #    would remove o from the results. So, in effect we are testing that
        #    we are promoting the fk_rel join to a left outer join here.
        # 2. The default value of 3 is generated for the case expression.
        self.assertQuerysetEqual(
            CaseTestModel.objects.filter(pk=o.pk).annotate(foo=Case(
                When(fk_rel__pk=1, then=2),
                default=3,
                output_field=models.IntegerField()), ), [(o, 3)], lambda x:
            (x, x.foo))
        # Now 2 should be generated, as the fk_rel is null.
        self.assertQuerysetEqual(
            CaseTestModel.objects.filter(pk=o.pk).annotate(foo=Case(
                When(fk_rel__isnull=True, then=2),
                default=3,
                output_field=models.IntegerField()), ), [(o, 2)], lambda x:
            (x, x.foo))

    def test_m2m_exclude(self):
        CaseTestModel.objects.create(integer=10, integer2=1, string='1')
        qs = CaseTestModel.objects.values_list('id', 'integer').annotate(
            cnt=models.Sum(
                Case(When(~Q(fk_rel__integer=1), then=1), default=2),
                output_field=models.IntegerField()), ).order_by('integer')
        # The first o has 2 as its fk_rel__integer=1, thus it hits the
        # default=2 case. The other ones have 2 as the result as they have 2
        # fk_rel objects, except for integer=4 and integer=10 (created above).
        # The integer=4 case has one integer, thus the result is 1, and
        # integer=10 doesn't have any and this too generates 1 (instead of 0)
        # as ~Q() also matches nulls.
        self.assertQuerysetEqual(qs, [(1, 2), (2, 2), (2, 2), (3, 2), (3, 2),
                                      (3, 2), (4, 1), (10, 1)],
                                 lambda x: x[1:])

    def test_m2m_reuse(self):
        CaseTestModel.objects.create(integer=10, integer2=1, string='1')
        # Need to use values before annotate so that Oracle will not group
        # by fields it isn't capable of grouping by.
        qs = CaseTestModel.objects.values_list('id', 'integer').annotate(
            cnt=models.Sum(Case(When(~Q(fk_rel__integer=1), then=1),
                                default=2),
                           output_field=models.IntegerField()),
        ).annotate(cnt2=models.Sum(
            Case(When(~Q(fk_rel__integer=1), then=1), default=2),
            output_field=models.IntegerField()), ).order_by('integer')
        self.assertEqual(str(qs.query).count(' JOIN '), 1)
        self.assertQuerysetEqual(qs,
                                 [(1, 2, 2), (2, 2, 2), (2, 2, 2), (3, 2, 2),
                                  (3, 2, 2), (3, 2, 2), (4, 1, 1),
                                  (10, 1, 1)], lambda x: x[1:])
Exemplo n.º 28
0
def expected_failure_if_grappelli(func):
    if 'grappelli' in settings.INSTALLED_APPS:
        return unittest.expectedFailure(func)
    return func
Exemplo n.º 29
0
def expectedFailurePY2(func):
    if not PY2:
        return func
    return unittest.expectedFailure(func)
Exemplo n.º 30
0
class BuilderTest(unittest.TestCase):
    def setUp(self):
        self.builder = builder.AstroidBuilder()

    def test_data_build_null_bytes(self):
        with self.assertRaises(exceptions.AstroidSyntaxError):
            self.builder.string_build('\x00')

    def test_data_build_invalid_x_escape(self):
        with self.assertRaises(exceptions.AstroidSyntaxError):
            self.builder.string_build('"\\x1"')

    def test_missing_newline(self):
        """check that a file with no trailing new line is parseable"""
        resources.build_file('data/noendingnewline.py')

    def test_missing_file(self):
        with self.assertRaises(exceptions.AstroidBuildingError):
            resources.build_file('data/inexistant.py')

    def test_inspect_build0(self):
        """test astroid tree build from a living object"""
        builtin_ast = MANAGER.ast_from_module_name(BUILTINS)
        # just check type and object are there
        builtin_ast.getattr('type')
        objectastroid = builtin_ast.getattr('object')[0]
        self.assertIsInstance(
            objectastroid.getattr('__new__')[0], nodes.FunctionDef)
        # check open file alias
        builtin_ast.getattr('open')
        # check 'help' is there (defined dynamically by site.py)
        builtin_ast.getattr('help')
        # check property has __init__
        pclass = builtin_ast['property']
        self.assertIn('__init__', pclass)
        self.assertIsInstance(builtin_ast['None'], nodes.Const)
        self.assertIsInstance(builtin_ast['True'], nodes.Const)
        self.assertIsInstance(builtin_ast['False'], nodes.Const)
        self.assertIsInstance(builtin_ast['Exception'], nodes.ClassDef)
        self.assertIsInstance(builtin_ast['NotImplementedError'],
                              nodes.ClassDef)

    def test_inspect_build1(self):
        time_ast = MANAGER.ast_from_module_name('time')
        self.assertTrue(time_ast)
        self.assertEqual(time_ast['time'].args.defaults, [])

    if os.name == 'java':
        test_inspect_build1 = unittest.expectedFailure(test_inspect_build1)

    def test_inspect_build2(self):
        """test astroid tree build from a living object"""
        try:
            from mx import DateTime
        except ImportError:
            self.skipTest('test skipped: mxDateTime is not available')
        else:
            dt_ast = self.builder.inspect_build(DateTime)
            dt_ast.getattr('DateTime')
            # this one is failing since DateTimeType.__module__ = 'builtins' !
            #dt_ast.getattr('DateTimeType')

    def test_inspect_build3(self):
        self.builder.inspect_build(unittest)

    @test_utils.require_version(maxver='3.0')
    def test_inspect_build_instance(self):
        """test astroid tree build from a living object"""
        import exceptions as builtin_exceptions
        builtin_ast = self.builder.inspect_build(builtin_exceptions)
        fclass = builtin_ast['OSError']
        # things like OSError.strerror are now (2.5) data descriptors on the
        # class instead of entries in the __dict__ of an instance
        container = fclass
        self.assertIn('errno', container)
        self.assertIn('strerror', container)
        self.assertIn('filename', container)

    def test_inspect_build_type_object(self):
        builtin_ast = MANAGER.ast_from_module_name(BUILTINS)

        inferred = list(builtin_ast.igetattr('object'))
        self.assertEqual(len(inferred), 1)
        inferred = inferred[0]
        self.assertEqual(inferred.name, 'object')
        inferred.as_string()  # no crash test

        inferred = list(builtin_ast.igetattr('type'))
        self.assertEqual(len(inferred), 1)
        inferred = inferred[0]
        self.assertEqual(inferred.name, 'type')
        inferred.as_string()  # no crash test

    def test_inspect_transform_module(self):
        # ensure no cached version of the time module
        MANAGER._mod_file_cache.pop(('time', None), None)
        MANAGER.astroid_cache.pop('time', None)

        def transform_time(node):
            if node.name == 'time':
                node.transformed = True

        MANAGER.register_transform(nodes.Module, transform_time)
        try:
            time_ast = MANAGER.ast_from_module_name('time')
            self.assertTrue(getattr(time_ast, 'transformed', False))
        finally:
            MANAGER.unregister_transform(nodes.Module, transform_time)

    def test_package_name(self):
        """test base properties and method of a astroid module"""
        datap = resources.build_file('data/__init__.py', 'data')
        self.assertEqual(datap.name, 'data')
        self.assertEqual(datap.package, 1)
        datap = resources.build_file('data/__init__.py', 'data.__init__')
        self.assertEqual(datap.name, 'data')
        self.assertEqual(datap.package, 1)
        datap = resources.build_file('data/tmp__init__.py', 'data.tmp__init__')
        self.assertEqual(datap.name, 'data.tmp__init__')
        self.assertEqual(datap.package, 0)

    def test_yield_parent(self):
        """check if we added discard nodes as yield parent (w/ compiler)"""
        code = """
            def yiell(): #@
                yield 0
                if noe:
                    yield more
        """
        func = builder.extract_node(code)
        self.assertIsInstance(func, nodes.FunctionDef)
        stmt = func.body[0]
        self.assertIsInstance(stmt, nodes.Expr)
        self.assertIsInstance(stmt.value, nodes.Yield)
        self.assertIsInstance(func.body[1].body[0], nodes.Expr)
        self.assertIsInstance(func.body[1].body[0].value, nodes.Yield)

    def test_object(self):
        obj_ast = self.builder.inspect_build(object)
        self.assertIn('__setattr__', obj_ast)

    def test_newstyle_detection(self):
        data = '''
            class A:
                "old style"

            class B(A):
                "old style"

            class C(object):
                "new style"

            class D(C):
                "new style"

            __metaclass__ = type

            class E(A):
                "old style"

            class F:
                "new style"
        '''
        mod_ast = builder.parse(data, __name__)
        self.assertTrue(mod_ast['A'].newstyle)
        self.assertTrue(mod_ast['B'].newstyle)
        self.assertTrue(mod_ast['E'].newstyle)
        self.assertTrue(mod_ast['C'].newstyle)
        self.assertTrue(mod_ast['D'].newstyle)
        self.assertTrue(mod_ast['F'].newstyle)

    def test_globals(self):
        data = '''
            CSTE = 1

            def update_global():
                global CSTE
                CSTE += 1

            def global_no_effect():
                global CSTE2
                print (CSTE)
        '''
        astroid = builder.parse(data, __name__)
        self.assertEqual(len(astroid.getattr('CSTE')), 2)
        self.assertIsInstance(astroid.getattr('CSTE')[0], nodes.AssignName)
        self.assertEqual(astroid.getattr('CSTE')[0].fromlineno, 2)
        self.assertEqual(astroid.getattr('CSTE')[1].fromlineno, 6)
        with self.assertRaises(exceptions.AttributeInferenceError):
            astroid.getattr('CSTE2')
        with self.assertRaises(exceptions.InferenceError):
            next(astroid['global_no_effect'].ilookup('CSTE2'))

    def test_socket_build(self):
        import socket
        astroid = self.builder.module_build(socket)
        # XXX just check the first one. Actually 3 objects are inferred (look at
        # the socket module) but the last one as those attributes dynamically
        # set and astroid is missing this.
        for fclass in astroid.igetattr('socket'):
            self.assertIn('connect', fclass)
            self.assertIn('send', fclass)
            self.assertIn('close', fclass)
            break

    def test_gen_expr_var_scope(self):
        data = 'l = list(n for n in range(10))\n'
        astroid = builder.parse(data, __name__)
        # n unavailable outside gen expr scope
        self.assertNotIn('n', astroid)
        # test n is inferable anyway
        n = test_utils.get_name_node(astroid, 'n')
        self.assertIsNot(n.scope(), astroid)
        self.assertEqual([i.__class__ for i in n.infer()],
                         [util.Uninferable.__class__])

    def test_no_future_imports(self):
        mod = builder.parse("import sys")
        self.assertEqual(set(), mod.future_imports)

    def test_future_imports(self):
        mod = builder.parse("from __future__ import print_function")
        self.assertEqual({'print_function'}, mod.future_imports)

    def test_two_future_imports(self):
        mod = builder.parse("""
            from __future__ import print_function
            from __future__ import absolute_import
            """)
        self.assertEqual({'print_function', 'absolute_import'},
                         mod.future_imports)

    def test_inferred_build(self):
        code = '''
            class A: pass
            A.type = "class"

            def A_assign_type(self):
                print (self)
            A.assign_type = A_assign_type
            '''
        astroid = builder.parse(code)
        lclass = list(astroid.igetattr('A'))
        self.assertEqual(len(lclass), 1)
        lclass = lclass[0]
        self.assertIn('assign_type', lclass.locals)
        self.assertIn('type', lclass.locals)

    def test_augassign_attr(self):
        builder.parse(
            """
            class Counter:
                v = 0
                def inc(self):
                    self.v += 1
            """, __name__)
        # TODO: Check self.v += 1 generate AugAssign(AssAttr(...)),
        # not AugAssign(GetAttr(AssName...))

    def test_inferred_dont_pollute(self):
        code = '''
            def func(a=None):
                a.custom_attr = 0
            def func2(a={}):
                a.custom_attr = 0
            '''
        builder.parse(code)
        nonetype = nodes.const_factory(None)
        # pylint: disable=no-member; Infers two potential values
        self.assertNotIn('custom_attr', nonetype.locals)
        self.assertNotIn('custom_attr', nonetype.instance_attrs)
        nonetype = nodes.const_factory({})
        self.assertNotIn('custom_attr', nonetype.locals)
        self.assertNotIn('custom_attr', nonetype.instance_attrs)

    def test_asstuple(self):
        code = 'a, b = range(2)'
        astroid = builder.parse(code)
        self.assertIn('b', astroid.locals)
        code = '''
            def visit_if(self, node):
                node.test, body = node.tests[0]
            '''
        astroid = builder.parse(code)
        self.assertIn('body', astroid['visit_if'].locals)

    def test_build_constants(self):
        '''test expected values of constants after rebuilding'''
        code = '''
            def func():
                return None
                return
                return 'None'
            '''
        astroid = builder.parse(code)
        none, nothing, chain = [ret.value for ret in astroid.body[0].body]
        self.assertIsInstance(none, nodes.Const)
        self.assertIsNone(none.value)
        self.assertIsNone(nothing)
        self.assertIsInstance(chain, nodes.Const)
        self.assertEqual(chain.value, 'None')

    def test_not_implemented(self):
        node = builder.extract_node('''
        NotImplemented #@
        ''')
        inferred = next(node.infer())
        self.assertIsInstance(inferred, nodes.Const)
        self.assertEqual(inferred.value, NotImplemented)
Exemplo n.º 31
0
        self.assertObjectsAt(sg, imath.Box2f(imath.V2f(0), imath.V2f(1)),
                             ["/group/plane"])

        sg.setSelectionMask(IECore.StringVectorData(["Camera"]))

        self.assertObjectsAt(sg, imath.Box2f(imath.V2f(0), imath.V2f(1)),
                             ["/group/camera"])

    def setUp(self):

        GafferUITest.TestCase.setUp(self)

        self.__cachedConverterMaxMemory = IECoreGL.CachedConverter.defaultCachedConverter(
        ).getMaxMemory()

    def tearDown(self):

        GafferUITest.TestCase.tearDown(self)

        IECoreGL.CachedConverter.defaultCachedConverter().setMaxMemory(
            self.__cachedConverterMaxMemory)


if "TRAVIS" in os.environ:
    SceneGadgetTest.testExpansion = unittest.expectedFailure(
        SceneGadgetTest.testExpansion)

if __name__ == "__main__":
    unittest.main()
Exemplo n.º 32
0
class ModelTests(TestCase):
    # The bug is that the following queries would raise:
    # "TypeError: Related Field has invalid lookup: gte"
    def test_related_gte_lookup(self):
        """
        Regression test for #10153: foreign key __gte lookups.
        """
        Worker.objects.filter(department__gte=0)

    def test_related_lte_lookup(self):
        """
        Regression test for #10153: foreign key __lte lookups.
        """
        Worker.objects.filter(department__lte=0)

    def test_sql_insert_compiler_return_id_attribute(self):
        """
        Regression test for #14019: SQLInsertCompiler.as_sql() failure
        """
        db = router.db_for_write(Party)
        query = InsertQuery(Party)
        query.insert_values([Party._meta.fields[0]], [], raw=False)
        # this line will raise an AttributeError without the accompanying fix
        query.get_compiler(using=db).as_sql()

    def test_empty_choice(self):
        # NOTE: Part of the regression test here is merely parsing the model
        # declaration. The verbose_name, in particular, did not always work.
        a = Article.objects.create(headline="Look at me!",
                                   pub_date=datetime.datetime.now())
        # An empty choice field should return None for the display name.
        self.assertIs(a.get_status_display(), None)

        # Empty strings should be returned as Unicode
        a = Article.objects.get(pk=a.pk)
        self.assertEqual(a.misc_data, '')
        self.assertIs(type(a.misc_data), six.text_type)

    def test_long_textfield(self):
        # TextFields can hold more than 4000 characters (this was broken in
        # Oracle).
        a = Article.objects.create(headline="Really, really big",
                                   pub_date=datetime.datetime.now(),
                                   article_text="ABCDE" * 1000)
        a = Article.objects.get(pk=a.pk)
        self.assertEqual(len(a.article_text), 5000)

    def test_long_unicode_textfield(self):
        # TextFields can hold more than 4000 bytes also when they are
        # less than 4000 characters
        a = Article.objects.create(headline="Really, really big",
                                   pub_date=datetime.datetime.now(),
                                   article_text='\u05d0\u05d1\u05d2' * 1000)
        a = Article.objects.get(pk=a.pk)
        self.assertEqual(len(a.article_text), 3000)

    def test_date_lookup(self):
        # Regression test for #659
        Party.objects.create(when=datetime.datetime(1999, 12, 31))
        Party.objects.create(when=datetime.datetime(1998, 12, 31))
        Party.objects.create(when=datetime.datetime(1999, 1, 1))
        Party.objects.create(when=datetime.datetime(1, 3, 3))
        self.assertQuerysetEqual(Party.objects.filter(when__month=2), [])
        self.assertQuerysetEqual(Party.objects.filter(when__month=1),
                                 [datetime.date(1999, 1, 1)],
                                 attrgetter("when"))
        self.assertQuerysetEqual(Party.objects.filter(when__month=12), [
            datetime.date(1999, 12, 31),
            datetime.date(1998, 12, 31),
        ],
                                 attrgetter("when"),
                                 ordered=False)
        self.assertQuerysetEqual(Party.objects.filter(when__year=1998), [
            datetime.date(1998, 12, 31),
        ], attrgetter("when"))
        # Regression test for #8510
        self.assertQuerysetEqual(Party.objects.filter(when__day="31"), [
            datetime.date(1999, 12, 31),
            datetime.date(1998, 12, 31),
        ],
                                 attrgetter("when"),
                                 ordered=False)
        self.assertQuerysetEqual(Party.objects.filter(when__month="12"), [
            datetime.date(1999, 12, 31),
            datetime.date(1998, 12, 31),
        ],
                                 attrgetter("when"),
                                 ordered=False)
        self.assertQuerysetEqual(Party.objects.filter(when__year="1998"), [
            datetime.date(1998, 12, 31),
        ], attrgetter("when"))

        # Regression test for #18969
        self.assertQuerysetEqual(Party.objects.filter(when__year=1), [
            datetime.date(1, 3, 3),
        ], attrgetter("when"))
        self.assertQuerysetEqual(Party.objects.filter(when__year='1'), [
            datetime.date(1, 3, 3),
        ], attrgetter("when"))

    if (3, ) <= sys.version_info < (3, 3) and connection.vendor == 'mysql':
        # In Python < 3.3, datetime.strftime raises an exception for years
        # below 1000, and existing MySQL DB-API drivers hit this problem.
        test_date_lookup = unittest.expectedFailure(test_date_lookup)

    def test_date_filter_null(self):
        # Date filtering was failing with NULL date values in SQLite
        # (regression test for #3501, among other things).
        Party.objects.create(when=datetime.datetime(1999, 1, 1))
        Party.objects.create()
        p = Party.objects.filter(when__month=1)[0]
        self.assertEqual(p.when, datetime.date(1999, 1, 1))
        self.assertQuerysetEqual(
            Party.objects.filter(pk=p.pk).dates("when", "month"), [1],
            attrgetter("month"))

    def test_get_next_prev_by_field(self):
        # Check that get_next_by_FIELD and get_previous_by_FIELD don't crash
        # when we have usecs values stored on the database
        #
        # It crashed after the Field.get_db_prep_* refactor, because on most
        # backends DateTimeFields supports usecs, but DateTimeField.to_python
        # didn't recognize them. (Note that
        # Model._get_next_or_previous_by_FIELD coerces values to strings)
        Event.objects.create(when=datetime.datetime(2000, 1, 1, 16, 0, 0))
        Event.objects.create(when=datetime.datetime(2000, 1, 1, 6, 1, 1))
        Event.objects.create(when=datetime.datetime(2000, 1, 1, 13, 1, 1))
        e = Event.objects.create(
            when=datetime.datetime(2000, 1, 1, 12, 0, 20, 24))

        self.assertEqual(e.get_next_by_when().when,
                         datetime.datetime(2000, 1, 1, 13, 1, 1))
        self.assertEqual(e.get_previous_by_when().when,
                         datetime.datetime(2000, 1, 1, 6, 1, 1))

    def test_primary_key_foreign_key_types(self):
        # Check Department and Worker (non-default PK type)
        d = Department.objects.create(id=10, name="IT")
        w = Worker.objects.create(department=d, name="Full-time")
        self.assertEqual(six.text_type(w), "Full-time")

    def test_broken_unicode(self):
        # Models with broken unicode methods should still have a printable repr
        b = BrokenUnicodeMethod.objects.create(name="Jerry")
        self.assertEqual(repr(b), "<BrokenUnicodeMethod: [Bad Unicode data]>")

    @skipUnlessDBFeature("supports_timezones")
    def test_timezones(self):
        # Saving an updating with timezone-aware datetime Python objects.
        # Regression test for #10443.
        # The idea is that all these creations and saving should work without
        # crashing. It's not rocket science.
        dt1 = datetime.datetime(2008,
                                8,
                                31,
                                16,
                                20,
                                tzinfo=get_fixed_timezone(600))
        dt2 = datetime.datetime(2008,
                                8,
                                31,
                                17,
                                20,
                                tzinfo=get_fixed_timezone(600))
        obj = Article.objects.create(headline="A headline",
                                     pub_date=dt1,
                                     article_text="foo")
        obj.pub_date = dt2
        obj.save()
        self.assertEqual(
            Article.objects.filter(headline="A headline").update(pub_date=dt1),
            1)

    def test_chained_fks(self):
        """
        Regression for #18432: Chained foreign keys with to_field produce incorrect query
        """

        m1 = Model1.objects.create(pkey=1000)
        m2 = Model2.objects.create(model1=m1)
        m3 = Model3.objects.create(model2=m2)

        # this is the actual test for #18432
        m3 = Model3.objects.get(model2=1000)
        m3.model2
Exemplo n.º 33
0
class PyOtherFileTests(OtherFileTests, unittest.TestCase):
    FileIO = _pyio.FileIO
    modulename = '_pyio'

    # TODO: RUSTPYTHON
    if sys.platform == "win32":

        @unittest.expectedFailure
        def testBytesOpen(self):
            super().testBytesOpen()

    # TODO: RUSTPYTHON
    if sys.platform == "win32":

        @unittest.expectedFailure
        def testInvalidFd(self):
            super().testInvalidFd()

    # TODO: RUSTPYTHON
    if sys.platform == "win32":

        @unittest.expectedFailure
        def testModeStrings(self):
            super().testModeStrings()

    # TODO: RUSTPYTHON
    if sys.platform == "win32":

        @unittest.expectedFailure
        def testTruncate(self):
            super().testTruncate()

    # TODO: RUSTPYTHON
    if sys.platform == "win32":

        @unittest.expectedFailure
        def testTruncateOnWindows(self):
            super().testTruncateOnWindows()

    # TODO: RUSTPYTHON
    if sys.platform == "win32":

        @unittest.expectedFailure
        def testUnclosedFDOnException(self):
            super().testUnclosedFDOnException()

    # TODO: RUSTPYTHON
    if sys.platform == "win32":

        @unittest.expectedFailure
        def testUnicodeOpen(self):
            super().testUnicodeOpen()

    # TODO: RUSTPYTHON
    if sys.platform == "win32":

        @unittest.expectedFailure
        def testUtf8BytesOpen(self):
            super().testUtf8BytesOpen()

    def test_open_code(self):
        # Check that the default behaviour of open_code matches
        # open("rb")
        with self.FileIO(__file__, "rb") as f:
            expected = f.read()
        with check_warnings(quiet=True) as w:
            # Always test _open_code_with_warning
            with _pyio._open_code_with_warning(__file__) as f:
                actual = f.read()
            self.assertEqual(expected, actual)
            self.assertNotEqual(w.warnings, [])

    # TODO: RUSTPYTHON
    if sys.platform == "win32":
        test_open_code = unittest.expectedFailure(test_open_code)
Exemplo n.º 34
0
    'zfnet512_opset9': _S3_DOWNLOAD_ONNX + 'opset_9/zfnet512.tar.gz',
}

backend_name = pytest.config.getoption('backend', default='CPU')

if backend_name != 'INTERPRETER':
    # Set backend device name to be used instead of hardcoded by ONNX BackendTest class ones.
    NgraphBackend.backend_name = backend_name

    # import all test cases at global scope to make them visible to python.unittest
    backend_test = ModelZooTestRunner(NgraphBackend, zoo_models, __name__)
    test_cases = backend_test.test_cases['OnnxBackendZooModelTest']

    # Exclude failing tests...
    # RuntimeError: Broadcast argument shape, target shape, and axes are incompatible.
    expectedFailure(test_cases.test_densenet121_opset3_cpu)
    expectedFailure(test_cases.test_densenet121_opset6_cpu)
    expectedFailure(test_cases.test_inception_v2_opset3_cpu)
    expectedFailure(test_cases.test_inception_v2_opset6_cpu)
    expectedFailure(test_cases.test_emotion_ferplus_opset2_cpu)

    # RuntimeError: BatchNormalization: only 'spatial' mode is supported.
    expectedFailure(test_cases.test_duc_resnet101_hdc_opset7_cpu)

    # RuntimeError: Subtract: Argument element types are inconsistent.
    expectedFailure(test_cases.test_arcface_lresnet100e_opset7_cpu)

    # RuntimeError: 'Dot': Paired axes do not have same length. (OpSet 3)
    expectedFailure(test_cases.test_resnet50_opset3_cpu)
    expectedFailure(test_cases.test_shufflenet_opset3_cpu)
    expectedFailure(test_cases.test_bvlc_alexnet_opset3_cpu)
Exemplo n.º 35
0
class FunctionTests(SimpleTestCase):
    def test_inputs(self):
        self.assertEqual(floatformat(7.7), '7.7')
        self.assertEqual(floatformat(7.0), '7')
        self.assertEqual(floatformat(0.7), '0.7')
        self.assertEqual(floatformat(0.07), '0.1')
        self.assertEqual(floatformat(0.007), '0.0')
        self.assertEqual(floatformat(0.0), '0')
        self.assertEqual(floatformat(7.7, 3), '7.700')
        self.assertEqual(floatformat(6.000000, 3), '6.000')
        self.assertEqual(floatformat(6.200000, 3), '6.200')
        self.assertEqual(floatformat(6.200000, -3), '6.200')
        self.assertEqual(floatformat(13.1031, -3), '13.103')
        self.assertEqual(floatformat(11.1197, -2), '11.12')
        self.assertEqual(floatformat(11.0000, -2), '11')
        self.assertEqual(floatformat(11.000001, -2), '11.00')
        self.assertEqual(floatformat(8.2798, 3), '8.280')
        self.assertEqual(floatformat(5555.555, 2), '5555.56')
        self.assertEqual(floatformat(001.3000, 2), '1.30')
        self.assertEqual(floatformat(0.12345, 2), '0.12')
        self.assertEqual(floatformat(Decimal('555.555'), 2), '555.56')
        self.assertEqual(floatformat(Decimal('09.000')), '9')
        self.assertEqual(floatformat('foo'), '')
        self.assertEqual(floatformat(13.1031, 'bar'), '13.1031')
        self.assertEqual(floatformat(18.125, 2), '18.13')
        self.assertEqual(floatformat('foo', 'bar'), '')
        self.assertEqual(floatformat('¿Cómo esta usted?'), '')
        self.assertEqual(floatformat(None), '')

    def test_zero_values(self):
        """
        Check that we're not converting to scientific notation.
        """
        self.assertEqual(floatformat(0, 6), '0.000000')
        self.assertEqual(floatformat(0, 7), '0.0000000')
        self.assertEqual(floatformat(0, 10), '0.0000000000')
        self.assertEqual(floatformat(0.000000000000000000015, 20),
                         '0.00000000000000000002')

    def test_infinity(self):
        pos_inf = float(1e30000)
        self.assertEqual(floatformat(pos_inf), six.text_type(pos_inf))

        neg_inf = float(-1e30000)
        self.assertEqual(floatformat(neg_inf), six.text_type(neg_inf))

        nan = pos_inf / pos_inf
        self.assertEqual(floatformat(nan), six.text_type(nan))

    def test_float_dunder_method(self):
        class FloatWrapper(object):
            def __init__(self, value):
                self.value = value

            def __float__(self):
                return self.value

        self.assertEqual(floatformat(FloatWrapper(11.000001), -2), '11.00')

    def test_low_decimal_precision(self):
        """
        #15789
        """
        with localcontext() as ctx:
            ctx.prec = 2
            self.assertEqual(floatformat(1.2345, 2), '1.23')
            self.assertEqual(floatformat(15.2042, -3), '15.204')
            self.assertEqual(floatformat(1.2345, '2'), '1.23')
            self.assertEqual(floatformat(15.2042, '-3'), '15.204')
            self.assertEqual(floatformat(Decimal('1.2345'), 2), '1.23')
            self.assertEqual(floatformat(Decimal('15.2042'), -3), '15.204')

    def test_many_zeroes(self):
        self.assertEqual(floatformat(1.00000000000000015, 16),
                         '1.0000000000000002')

    if six.PY2:
        # The above test fails because of Python 2's float handling. Floats
        # with many zeroes after the decimal point should be passed in as
        # another type such as unicode or Decimal.
        test_many_zeroes = expectedFailure(test_many_zeroes)
Exemplo n.º 36
0
def load_tests(loader, standard_tests, pattern):
    if sys.implementation.name == 'ironpython':
        suite = unittest.TestSuite()
        suite.addTest(test.test_memoryio.CBytesIOTest('testInit'))
        suite.addTest(test.test_memoryio.CBytesIOTest('testRead'))
        suite.addTest(test.test_memoryio.CBytesIOTest('testReadNoArgs'))
        suite.addTest(test.test_memoryio.CBytesIOTest('testSeek'))
        suite.addTest(test.test_memoryio.CBytesIOTest('testTell'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_bytes_array'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_detach'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_flags'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_flush'))
        suite.addTest(
            unittest.expectedFailure(
                test.test_memoryio.CBytesIOTest('test_getbuffer'))
        )  # https://github.com/IronLanguages/ironpython3/issues/1002
        suite.addTest(test.test_memoryio.CBytesIOTest('test_getstate'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_getvalue'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_init'))
        #suite.addTest(test.test_memoryio.CBytesIOTest('test_instance_dict_leak')) # https://github.com/IronLanguages/ironpython3/issues/1004
        suite.addTest(test.test_memoryio.CBytesIOTest('test_issue5449'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_iterator'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_overseek'))
        suite.addTest(
            unittest.expectedFailure(
                test.test_memoryio.CBytesIOTest('test_pickling'))
        )  # https://github.com/IronLanguages/ironpython3/issues/1003
        suite.addTest(test.test_memoryio.CBytesIOTest('test_read'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_read1'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_readinto'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_readline'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_readlines'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_relative_seek'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_seek'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_setstate'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_sizeof'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_subclassing'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_tell'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_truncate'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_unicode'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_write'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_writelines'))
        suite.addTest(test.test_memoryio.CBytesIOTest('test_writelines_error'))
        suite.addTest(test.test_memoryio.CStringIOPickleTest('test_issue5265'))
        suite.addTest(
            test.test_memoryio.CStringIOPickleTest('test_newline_argument'))
        suite.addTest(
            test.test_memoryio.CStringIOPickleTest('test_newline_cr'))
        suite.addTest(
            test.test_memoryio.CStringIOPickleTest('test_newline_crlf'))
        suite.addTest(
            test.test_memoryio.CStringIOPickleTest('test_newline_default'))
        suite.addTest(
            test.test_memoryio.CStringIOPickleTest('test_newline_empty'))
        suite.addTest(
            test.test_memoryio.CStringIOPickleTest('test_newline_lf'))
        suite.addTest(
            test.test_memoryio.CStringIOPickleTest('test_newline_none'))
        suite.addTest(
            test.test_memoryio.CStringIOPickleTest('test_newlines_property'))
        suite.addTest(
            test.test_memoryio.CStringIOPickleTest('test_relative_seek'))
        suite.addTest(
            test.test_memoryio.CStringIOPickleTest('test_textio_properties'))
        suite.addTest(test.test_memoryio.CStringIOTest('testInit'))
        suite.addTest(test.test_memoryio.CStringIOTest('testRead'))
        suite.addTest(test.test_memoryio.CStringIOTest('testReadNoArgs'))
        suite.addTest(test.test_memoryio.CStringIOTest('testSeek'))
        suite.addTest(test.test_memoryio.CStringIOTest('testTell'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_detach'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_flags'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_flush'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_getstate'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_getvalue'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_init'))
        #suite.addTest(test.test_memoryio.CStringIOTest('test_instance_dict_leak')) # https://github.com/IronLanguages/ironpython3/issues/1004
        suite.addTest(test.test_memoryio.CStringIOTest('test_issue5265'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_iterator'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_lone_surrogates'))
        suite.addTest(
            test.test_memoryio.CStringIOTest('test_newline_argument'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_newline_cr'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_newline_crlf'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_newline_default'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_newline_empty'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_newline_lf'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_newline_none'))
        suite.addTest(
            test.test_memoryio.CStringIOTest('test_newlines_property'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_overseek'))
        suite.addTest(
            unittest.expectedFailure(
                test.test_memoryio.CStringIOTest('test_pickling'))
        )  # https://github.com/IronLanguages/ironpython3/issues/1003
        suite.addTest(test.test_memoryio.CStringIOTest('test_read'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_readline'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_readlines'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_relative_seek'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_seek'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_setstate'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_subclassing'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_tell'))
        suite.addTest(
            test.test_memoryio.CStringIOTest('test_textio_properties'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_truncate'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_widechar'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_write'))
        suite.addTest(test.test_memoryio.CStringIOTest('test_writelines'))
        suite.addTest(
            test.test_memoryio.CStringIOTest('test_writelines_error'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('testInit'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('testRead'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('testReadNoArgs'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('testSeek'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('testTell'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_bytes_array'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_detach'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_flags'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_flush'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_getbuffer'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_getvalue'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_init'))
        suite.addTest(
            test.test_memoryio.PyBytesIOTest('test_instance_dict_leak'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_issue5449'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_iterator'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_overseek'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_pickling'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_read'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_read1'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_readinto'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_readline'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_readlines'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_relative_seek'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_seek'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_subclassing'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_tell'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_truncate'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_unicode'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_write'))
        suite.addTest(test.test_memoryio.PyBytesIOTest('test_writelines'))
        suite.addTest(
            test.test_memoryio.PyBytesIOTest('test_writelines_error'))
        suite.addTest(
            test.test_memoryio.PyStringIOPickleTest('test_issue5265'))
        suite.addTest(
            test.test_memoryio.PyStringIOPickleTest('test_newline_argument'))
        suite.addTest(
            test.test_memoryio.PyStringIOPickleTest('test_newline_cr'))
        suite.addTest(
            test.test_memoryio.PyStringIOPickleTest('test_newline_crlf'))
        suite.addTest(
            test.test_memoryio.PyStringIOPickleTest('test_newline_default'))
        suite.addTest(
            test.test_memoryio.PyStringIOPickleTest('test_newline_empty'))
        suite.addTest(
            test.test_memoryio.PyStringIOPickleTest('test_newline_lf'))
        suite.addTest(
            test.test_memoryio.PyStringIOPickleTest('test_newline_none'))
        suite.addTest(
            test.test_memoryio.PyStringIOPickleTest('test_newlines_property'))
        suite.addTest(
            test.test_memoryio.PyStringIOPickleTest('test_relative_seek'))
        suite.addTest(
            test.test_memoryio.PyStringIOPickleTest('test_textio_properties'))
        suite.addTest(test.test_memoryio.PyStringIOTest('testInit'))
        suite.addTest(test.test_memoryio.PyStringIOTest('testRead'))
        suite.addTest(test.test_memoryio.PyStringIOTest('testReadNoArgs'))
        suite.addTest(test.test_memoryio.PyStringIOTest('testSeek'))
        suite.addTest(test.test_memoryio.PyStringIOTest('testTell'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_detach'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_flags'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_flush'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_getvalue'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_init'))
        suite.addTest(
            test.test_memoryio.PyStringIOTest('test_instance_dict_leak'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_issue5265'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_iterator'))
        suite.addTest(
            test.test_memoryio.PyStringIOTest('test_lone_surrogates'))
        suite.addTest(
            test.test_memoryio.PyStringIOTest('test_newline_argument'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_newline_cr'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_newline_crlf'))
        suite.addTest(
            test.test_memoryio.PyStringIOTest('test_newline_default'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_newline_empty'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_newline_lf'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_newline_none'))
        suite.addTest(
            test.test_memoryio.PyStringIOTest('test_newlines_property'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_overseek'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_pickling'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_read'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_readline'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_readlines'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_relative_seek'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_seek'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_subclassing'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_tell'))
        suite.addTest(
            test.test_memoryio.PyStringIOTest('test_textio_properties'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_truncate'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_write'))
        suite.addTest(test.test_memoryio.PyStringIOTest('test_writelines'))
        suite.addTest(
            test.test_memoryio.PyStringIOTest('test_writelines_error'))
        return suite

    else:
        return loader.loadTestsFromModule(test.test_memoryio, pattern)
Exemplo n.º 37
0
def load_tests(loader, standard_tests, pattern):
    if sys.implementation.name == 'ironpython':
        suite = unittest.TestSuite()
        suite.addTest(test.test_httplib.BasicTest('test_bad_status_repr'))
        suite.addTest(test.test_httplib.BasicTest('test_chunked'))
        suite.addTest(test.test_httplib.BasicTest('test_chunked_head'))
        suite.addTest(test.test_httplib.BasicTest('test_delayed_ack_opt'))
        suite.addTest(test.test_httplib.BasicTest('test_early_eof'))
        suite.addTest(test.test_httplib.BasicTest('test_epipe'))
        suite.addTest(test.test_httplib.BasicTest('test_error_leak'))
        suite.addTest(test.test_httplib.BasicTest('test_host_port'))
        suite.addTest(test.test_httplib.BasicTest('test_incomplete_read'))
        suite.addTest(
            test.test_httplib.BasicTest('test_negative_content_length'))
        suite.addTest(
            test.test_httplib.BasicTest('test_overflowing_chunked_line'))
        suite.addTest(
            test.test_httplib.BasicTest('test_overflowing_header_line'))
        suite.addTest(
            test.test_httplib.BasicTest('test_overflowing_status_line'))
        suite.addTest(test.test_httplib.BasicTest('test_partial_readintos'))
        suite.addTest(
            test.test_httplib.BasicTest(
                'test_partial_readintos_incomplete_body'))
        suite.addTest(
            test.test_httplib.BasicTest(
                'test_partial_readintos_no_content_length'))
        suite.addTest(test.test_httplib.BasicTest('test_partial_reads'))
        suite.addTest(
            test.test_httplib.BasicTest('test_partial_reads_incomplete_body'))
        suite.addTest(
            test.test_httplib.BasicTest(
                'test_partial_reads_no_content_length'))
        suite.addTest(test.test_httplib.BasicTest('test_read_head'))
        suite.addTest(test.test_httplib.BasicTest('test_readinto_chunked'))
        suite.addTest(
            test.test_httplib.BasicTest('test_readinto_chunked_head'))
        suite.addTest(test.test_httplib.BasicTest('test_readinto_head'))
        suite.addTest(test.test_httplib.BasicTest('test_response_headers'))
        suite.addTest(test.test_httplib.BasicTest('test_send'))
        suite.addTest(test.test_httplib.BasicTest('test_send_file'))
        suite.addTest(test.test_httplib.BasicTest('test_send_iter'))
        suite.addTest(test.test_httplib.BasicTest('test_send_type_error'))
        suite.addTest(test.test_httplib.BasicTest('test_send_updating_file'))
        suite.addTest(test.test_httplib.BasicTest('test_status_lines'))
        suite.addTest(test.test_httplib.BasicTest('test_too_many_headers'))
        suite.addTest(
            test.test_httplib.HTTPResponseTest('test_getting_header'))
        suite.addTest(
            test.test_httplib.HTTPResponseTest(
                'test_getting_header_defaultint'))
        suite.addTest(
            test.test_httplib.HTTPResponseTest(
                'test_getting_nonexistent_header_with_iterable_default'))
        suite.addTest(
            test.test_httplib.HTTPResponseTest(
                'test_getting_nonexistent_header_with_string_default'))
        suite.addTest(
            test.test_httplib.HTTPResponseTest(
                'test_getting_nonexistent_header_without_default'))
        suite.addTest(test.test_httplib.HTTPSTest('test_attributes'))
        suite.addTest(test.test_httplib.HTTPSTest('test_host_port'))
        #suite.addTest(test.test_httplib.HTTPSTest('test_local_bad_hostname')) # StackOverflowException
        #suite.addTest(test.test_httplib.HTTPSTest('test_local_good_hostname')) # StackOverflowException
        #suite.addTest(test.test_httplib.HTTPSTest('test_local_unknown_cert')) # StackOverflowException
        suite.addTest(
            unittest.expectedFailure(
                test.test_httplib.HTTPSTest('test_networked'))
        )  # AttributeError: 'SSLError' object has no attribute 'reason'
        suite.addTest(
            unittest.expectedFailure(
                test.test_httplib.HTTPSTest('test_networked_bad_cert'))
        )  # AttributeError: 'SSLError' object has no attribute 'reason'
        suite.addTest(test.test_httplib.HTTPSTest('test_networked_good_cert'))
        suite.addTest(
            test.test_httplib.HTTPSTest('test_networked_noverification'))
        suite.addTest(
            test.test_httplib.HTTPSTest(
                'test_networked_trusted_by_default_cert'))
        suite.addTest(test.test_httplib.HeaderTests('test_auto_headers'))
        suite.addTest(test.test_httplib.HeaderTests('test_content_length_0'))
        suite.addTest(test.test_httplib.HeaderTests('test_invalid_headers'))
        suite.addTest(test.test_httplib.HeaderTests('test_ipv6host_header'))
        suite.addTest(
            test.test_httplib.HeaderTests('test_malformed_headers_coped_with'))
        suite.addTest(
            unittest.expectedFailure(
                test.test_httplib.HeaderTests('test_putheader'))
        )  # https://github.com/IronLanguages/ironpython3/issues/1100
        suite.addTest(test.test_httplib.OfflineTest('test_all'))
        suite.addTest(test.test_httplib.OfflineTest('test_responses'))
        suite.addTest(test.test_httplib.RequestBodyTest('test_ascii_body'))
        suite.addTest(
            test.test_httplib.RequestBodyTest('test_binary_file_body'))
        suite.addTest(test.test_httplib.RequestBodyTest('test_bytes_body'))
        suite.addTest(test.test_httplib.RequestBodyTest('test_file_body'))
        suite.addTest(test.test_httplib.RequestBodyTest('test_latin1_body'))
        suite.addTest(
            test.test_httplib.RequestBodyTest('test_manual_content_length'))
        suite.addTest(
            test.test_httplib.SourceAddressTest(
                'testHTTPConnectionSourceAddress'))
        suite.addTest(
            test.test_httplib.SourceAddressTest(
                'testHTTPSConnectionSourceAddress'))
        suite.addTest(test.test_httplib.TimeoutTest('testTimeoutAttribute'))
        suite.addTest(
            test.test_httplib.TunnelTests('test_connect_put_request'))
        suite.addTest(
            test.test_httplib.TunnelTests('test_connect_with_tunnel'))
        suite.addTest(
            test.test_httplib.TunnelTests(
                'test_disallow_set_tunnel_after_connect'))
        suite.addTest(
            test.test_httplib.TunnelTests('test_set_tunnel_host_port_headers'))
        return suite

    else:
        return loader.loadTestsFromModule(test.test_httplib, pattern)
def generateScriptTests():
    """Find all files in unit_tests/*.d/*.{lsl,run} and generate tests for
    them.
    """

    path = os.path.dirname(__file__)
    if path:
        os.chdir(path)

    testsuites = ('Regression', 'Coverage', 'Expr', 'LSO', 'Preproc')
    for testsuite in testsuites:
        files = glob.glob(
            os.path.join('unit_tests',
                         testsuite.lower() + '.suite', '*.lsl')) + glob.glob(
                             os.path.join('unit_tests',
                                          testsuite.lower() + '.suite',
                                          '*.run'))
        files = list(set([os.path.splitext(x)[0] for x in files]))
        files.sort()
        for fbase in files:
            # Create a closure with the test data
            def makeTestFunction(fbase, suite):
                def TestFunction(self):
                    stdin = tryRead(fbase + '.lsl') or b''
                    expected_stdout = tryRead(fbase + '.out') or b''
                    expected_stderr = tryRead(fbase + '.err') or b''
                    runargs = (
                        parseArgs(tryRead(fbase + '.run', Binary=False))
                        or (['main.py', '-y', '-'] if suite != 'Expr' else [
                            'main.py',
                            # Defaults for Expr:
                            '-O',
                            'clear,optimize,constfold'
                            ',addstrings,foldtabs,expr',
                            '-y',
                            '-'
                        ]))
                    werr(u"\nRunning test %s: " % any2u(fbase))
                    actual_stdout, actual_stderr = invokeMain(runargs, stdin)
                    actual_stdout = (actual_stdout.replace(
                        b'\r', b'\r\n').replace(b'\r\n\n',
                                                b'\n').replace(b'\r\n', b'\n'))

                    actual_stderr = (actual_stderr.replace(
                        b'\r', b'\r\n').replace(b'\r\n\n',
                                                b'\n').replace(b'\r\n', b'\n'))

                    try:
                        if expected_stderr.startswith(b'REGEX\n'):
                            self.assertIsNotNone(
                                re.search(b2u(expected_stderr[6:], 'utf8'),
                                          b2u(actual_stderr, 'utf8')))
                        else:
                            self.assertTrue(expected_stderr == actual_stderr)
                    except AssertionError:
                        werr(u'Failed' u'\n************ expected stderr:\n')
                        werr(expected_stderr)
                        werr(u'\n************ actual stderr:\n')
                        werr(actual_stderr)
                        if difflib and expected_stderr and actual_stderr \
                           and not expected_stderr.startswith(b'REGEX\n'):
                            werr(u'\n************ diff:\n' + u'\n'.join(
                                difflib.unified_diff(
                                    b2u(expected_stderr).split(u'\n'),
                                    b2u(actual_stderr).split(u'\n'),
                                    'expected',
                                    'actual',
                                    lineterm='')))
                        werr(u'\n************ ')
                        raise
                    try:
                        if expected_stdout.startswith(b'REGEX\n'):
                            self.assertIsNotNone(
                                re.search(b2u(expected_stdout[6:], 'utf8'),
                                          b2u(actual_stdout, 'utf8')))
                        else:
                            self.assertTrue(expected_stdout == actual_stdout)
                    except AssertionError:
                        werr(u'Failed' u'\n************ expected stdout:\n')
                        werr(expected_stdout)
                        werr(u'\n************ actual stdout:\n')
                        werr(actual_stdout)
                        if difflib and expected_stdout and actual_stdout \
                           and not expected_stdout.startswith(b'REGEX\n'):
                            werr(u'\n************ diff:\n' + u'\n'.join(
                                difflib.unified_diff(
                                    b2u(expected_stdout).split('\n'),
                                    b2u(actual_stdout).split('\n'),
                                    'expected',
                                    'actual',
                                    lineterm='')))
                        sys.stderr.write(u'\n************ ')
                        raise

                return TestFunction

            TestFunction = makeTestFunction(fbase, testsuite)
            # __doc__ is used by Eric
            line = b''
            try:
                f = open(fbase + '.lsl', 'rb')
                try:
                    line = f.readline()
                    if line.endswith(b'\r\n'):
                        line = line[:-2]
                    elif line[-1:] in (b'\r', b'\n'):
                        line = line[:-1]
                finally:
                    f.close()
            except IOError as e:
                if e.errno != 2:
                    raise
            TestFunction.__doc__ = (b2u(line[3:])
                                    if line.startswith(b'// ') else None)

            TestFunction.__name__ = ('test_' + testsuite + '__' +
                                     os.path.basename(fbase).replace('-', '_'))
            fail = tryRead(fbase + '.fail')
            if fail is not None:
                if fail:
                    TestFunction.__doc__ = b2u(fail)
                TestFunction = unittest.expectedFailure(TestFunction)
            else:
                skip = tryRead(fbase + '.skp')
                if skip is not None:
                    TestFunction = unittest.skip(skip)(TestFunction)
            setattr(globals()['UnitTest' + testsuite], TestFunction.__name__,
                    TestFunction)
Exemplo n.º 39
0
class CmdLineTest(unittest.TestCase):
    def _check_output(self,
                      script_name,
                      exit_code,
                      data,
                      expected_file,
                      expected_argv0,
                      expected_path0,
                      expected_package,
                      expected_loader,
                      expected_cwd=None):
        if verbose > 1:
            print("Output from test script %r:" % script_name)
            print(repr(data))
        self.assertEqual(exit_code, 0)
        printed_loader = '__loader__==%a' % expected_loader
        printed_file = '__file__==%a' % expected_file
        printed_package = '__package__==%r' % expected_package
        printed_argv0 = 'sys.argv[0]==%a' % expected_argv0
        printed_path0 = 'sys.path[0]==%a' % expected_path0
        if expected_cwd is None:
            expected_cwd = os.getcwd()
        printed_cwd = 'cwd==%a' % expected_cwd
        if verbose > 1:
            print('Expected output:')
            print(printed_file)
            print(printed_package)
            print(printed_argv0)
            print(printed_cwd)
        self.assertIn(printed_loader.encode('utf-8'), data)
        self.assertIn(printed_file.encode('utf-8'), data)
        self.assertIn(printed_package.encode('utf-8'), data)
        self.assertIn(printed_argv0.encode('utf-8'), data)
        self.assertIn(printed_path0.encode('utf-8'), data)
        self.assertIn(printed_cwd.encode('utf-8'), data)

    def _check_script(self,
                      script_exec_args,
                      expected_file,
                      expected_argv0,
                      expected_path0,
                      expected_package,
                      expected_loader,
                      *cmd_line_switches,
                      cwd=None,
                      **env_vars):
        if isinstance(script_exec_args, str):
            script_exec_args = [script_exec_args]
        run_args = [
            *support.optim_args_from_interpreter_flags(), *cmd_line_switches,
            *script_exec_args, *example_args
        ]
        rc, out, err = assert_python_ok(*run_args,
                                        __isolated=False,
                                        __cwd=cwd,
                                        **env_vars)
        self._check_output(script_exec_args, rc, out + err, expected_file,
                           expected_argv0, expected_path0, expected_package,
                           expected_loader, cwd)

    def _check_import_error(self,
                            script_exec_args,
                            expected_msg,
                            *cmd_line_switches,
                            cwd=None,
                            **env_vars):
        if isinstance(script_exec_args, str):
            script_exec_args = (script_exec_args, )
        else:
            script_exec_args = tuple(script_exec_args)
        run_args = cmd_line_switches + script_exec_args
        rc, out, err = assert_python_failure(*run_args,
                                             __isolated=False,
                                             __cwd=cwd,
                                             **env_vars)
        if verbose > 1:
            print(f'Output from test script {script_exec_args!r:}')
            print(repr(err))
            print('Expected output: %r' % expected_msg)
        self.assertIn(expected_msg.encode('utf-8'), err)

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_dash_c_loader(self):
        rc, out, err = assert_python_ok("-c", "print(__loader__)")
        expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8")
        self.assertIn(expected, out)

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_stdin_loader(self):
        # Unfortunately, there's no way to automatically test the fully
        # interactive REPL, since that code path only gets executed when
        # stdin is an interactive tty.
        p = spawn_python()
        try:
            p.stdin.write(b"print(__loader__)\n")
            p.stdin.flush()
        finally:
            out = kill_python(p)
        expected = repr(importlib.machinery.BuiltinImporter).encode("utf-8")
        self.assertIn(expected, out)

    @contextlib.contextmanager
    def interactive_python(self, separate_stderr=False):
        if separate_stderr:
            p = spawn_python('-i', stderr=subprocess.PIPE)
            stderr = p.stderr
        else:
            p = spawn_python('-i', stderr=subprocess.STDOUT)
            stderr = p.stdout
        try:
            # Drain stderr until prompt
            while True:
                data = stderr.read(4)
                if data == b">>> ":
                    break
                stderr.readline()
            yield p
        finally:
            kill_python(p)
            stderr.close()

    def check_repl_stdout_flush(self, separate_stderr=False):
        with self.interactive_python(separate_stderr) as p:
            p.stdin.write(b"print('foo')\n")
            p.stdin.flush()
            self.assertEqual(b'foo', p.stdout.readline().strip())

    def check_repl_stderr_flush(self, separate_stderr=False):
        with self.interactive_python(separate_stderr) as p:
            p.stdin.write(b"1/0\n")
            p.stdin.flush()
            stderr = p.stderr if separate_stderr else p.stdout
            self.assertIn(b'Traceback ', stderr.readline())
            self.assertIn(b'File "<stdin>"', stderr.readline())
            self.assertIn(b'ZeroDivisionError', stderr.readline())

    @unittest.skip("TODO: RUSTPYTHON, test hang in middle")
    def test_repl_stdout_flush(self):
        self.check_repl_stdout_flush()

    @unittest.skip("TODO: RUSTPYTHON, test hang in middle")
    def test_repl_stdout_flush_separate_stderr(self):
        self.check_repl_stdout_flush(True)

    @unittest.skip("TODO: RUSTPYTHON, test hang in middle")
    def test_repl_stderr_flush(self):
        self.check_repl_stderr_flush()

    @unittest.skip("TODO: RUSTPYTHON, test hang in middle")
    def test_repl_stderr_flush_separate_stderr(self):
        self.check_repl_stderr_flush(True)

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_basic_script(self):
        with support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, 'script')
            self._check_script(script_name, script_name, script_name,
                               script_dir, None,
                               importlib.machinery.SourceFileLoader)

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_script_compiled(self):
        with support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, 'script')
            py_compile.compile(script_name, doraise=True)
            os.remove(script_name)
            pyc_file = support.make_legacy_pyc(script_name)
            self._check_script(pyc_file, pyc_file, pyc_file, script_dir, None,
                               importlib.machinery.SourcelessFileLoader)

    def test_directory(self):
        with support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, '__main__')
            self._check_script(script_dir, script_name, script_dir, script_dir,
                               '', importlib.machinery.SourceFileLoader)

    def test_directory_compiled(self):
        with support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, '__main__')
            py_compile.compile(script_name, doraise=True)
            os.remove(script_name)
            pyc_file = support.make_legacy_pyc(script_name)
            self._check_script(script_dir, pyc_file, script_dir, script_dir,
                               '', importlib.machinery.SourcelessFileLoader)

    def test_directory_error(self):
        with support.temp_dir() as script_dir:
            msg = "can't find '__main__' module in %r" % script_dir
            self._check_import_error(script_dir, msg)

    def test_zipfile(self):
        with support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, '__main__')
            zip_name, run_name = make_zip_script(script_dir, 'test_zip',
                                                 script_name)
            self._check_script(zip_name, run_name, zip_name, zip_name, '',
                               zipimport.zipimporter)

    def test_zipfile_compiled_timestamp(self):
        with support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, '__main__')
            compiled_name = py_compile.compile(
                script_name,
                doraise=True,
                invalidation_mode=py_compile.PycInvalidationMode.TIMESTAMP)
            zip_name, run_name = make_zip_script(script_dir, 'test_zip',
                                                 compiled_name)
            self._check_script(zip_name, run_name, zip_name, zip_name, '',
                               zipimport.zipimporter)

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_zipfile_compiled_checked_hash(self):
        with support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, '__main__')
            compiled_name = py_compile.compile(
                script_name,
                doraise=True,
                invalidation_mode=py_compile.PycInvalidationMode.CHECKED_HASH)
            zip_name, run_name = make_zip_script(script_dir, 'test_zip',
                                                 compiled_name)
            self._check_script(zip_name, run_name, zip_name, zip_name, '',
                               zipimport.zipimporter)

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_zipfile_compiled_unchecked_hash(self):
        with support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, '__main__')
            compiled_name = py_compile.compile(
                script_name,
                doraise=True,
                invalidation_mode=py_compile.PycInvalidationMode.UNCHECKED_HASH
            )
            zip_name, run_name = make_zip_script(script_dir, 'test_zip',
                                                 compiled_name)
            self._check_script(zip_name, run_name, zip_name, zip_name, '',
                               zipimport.zipimporter)

    def test_zipfile_error(self):
        with support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, 'not_main')
            zip_name, run_name = make_zip_script(script_dir, 'test_zip',
                                                 script_name)
            msg = "can't find '__main__' module in %r" % zip_name
            self._check_import_error(zip_name, msg)

    def test_module_in_package(self):
        with support.temp_dir() as script_dir:
            pkg_dir = os.path.join(script_dir, 'test_pkg')
            make_pkg(pkg_dir)
            script_name = _make_test_script(pkg_dir, 'script')
            self._check_script(["-m", "test_pkg.script"],
                               script_name,
                               script_name,
                               script_dir,
                               'test_pkg',
                               importlib.machinery.SourceFileLoader,
                               cwd=script_dir)

    def test_module_in_package_in_zipfile(self):
        with support.temp_dir() as script_dir:
            zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip',
                                                    'test_pkg', 'script')
            self._check_script(["-m", "test_pkg.script"],
                               run_name,
                               run_name,
                               script_dir,
                               'test_pkg',
                               zipimport.zipimporter,
                               PYTHONPATH=zip_name,
                               cwd=script_dir)

    def test_module_in_subpackage_in_zipfile(self):
        with support.temp_dir() as script_dir:
            zip_name, run_name = _make_test_zip_pkg(script_dir,
                                                    'test_zip',
                                                    'test_pkg',
                                                    'script',
                                                    depth=2)
            self._check_script(["-m", "test_pkg.test_pkg.script"],
                               run_name,
                               run_name,
                               script_dir,
                               'test_pkg.test_pkg',
                               zipimport.zipimporter,
                               PYTHONPATH=zip_name,
                               cwd=script_dir)

    def test_package(self):
        with support.temp_dir() as script_dir:
            pkg_dir = os.path.join(script_dir, 'test_pkg')
            make_pkg(pkg_dir)
            script_name = _make_test_script(pkg_dir, '__main__')
            self._check_script(["-m", "test_pkg"],
                               script_name,
                               script_name,
                               script_dir,
                               'test_pkg',
                               importlib.machinery.SourceFileLoader,
                               cwd=script_dir)

    def test_package_compiled(self):
        with support.temp_dir() as script_dir:
            pkg_dir = os.path.join(script_dir, 'test_pkg')
            make_pkg(pkg_dir)
            script_name = _make_test_script(pkg_dir, '__main__')
            compiled_name = py_compile.compile(script_name, doraise=True)
            os.remove(script_name)
            pyc_file = support.make_legacy_pyc(script_name)
            self._check_script(["-m", "test_pkg"],
                               pyc_file,
                               pyc_file,
                               script_dir,
                               'test_pkg',
                               importlib.machinery.SourcelessFileLoader,
                               cwd=script_dir)

    def test_package_error(self):
        with support.temp_dir() as script_dir:
            pkg_dir = os.path.join(script_dir, 'test_pkg')
            make_pkg(pkg_dir)
            msg = ("'test_pkg' is a package and cannot "
                   "be directly executed")
            self._check_import_error(["-m", "test_pkg"], msg, cwd=script_dir)

    def test_package_recursion(self):
        with support.temp_dir() as script_dir:
            pkg_dir = os.path.join(script_dir, 'test_pkg')
            make_pkg(pkg_dir)
            main_dir = os.path.join(pkg_dir, '__main__')
            make_pkg(main_dir)
            msg = ("Cannot use package as __main__ module; "
                   "'test_pkg' is a package and cannot "
                   "be directly executed")
            self._check_import_error(["-m", "test_pkg"], msg, cwd=script_dir)

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_issue8202(self):
        # Make sure package __init__ modules see "-m" in sys.argv0 while
        # searching for the module to execute
        with support.temp_dir() as script_dir:
            with support.change_cwd(path=script_dir):
                pkg_dir = os.path.join(script_dir, 'test_pkg')
                make_pkg(pkg_dir,
                         "import sys; print('init_argv0==%r' % sys.argv[0])")
                script_name = _make_test_script(pkg_dir, 'script')
                rc, out, err = assert_python_ok('-m',
                                                'test_pkg.script',
                                                *example_args,
                                                __isolated=False)
                if verbose > 1:
                    print(repr(out))
                expected = "init_argv0==%r" % '-m'
                self.assertIn(expected.encode('utf-8'), out)
                self._check_output(script_name, rc, out, script_name,
                                   script_name, script_dir, 'test_pkg',
                                   importlib.machinery.SourceFileLoader)

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_issue8202_dash_c_file_ignored(self):
        # Make sure a "-c" file in the current directory
        # does not alter the value of sys.path[0]
        with support.temp_dir() as script_dir:
            with support.change_cwd(path=script_dir):
                with open("-c", "w") as f:
                    f.write("data")
                    rc, out, err = assert_python_ok(
                        '-c',
                        'import sys; print("sys.path[0]==%r" % sys.path[0])',
                        __isolated=False)
                    if verbose > 1:
                        print(repr(out))
                    expected = "sys.path[0]==%r" % ''
                    self.assertIn(expected.encode('utf-8'), out)

    def test_issue8202_dash_m_file_ignored(self):
        # Make sure a "-m" file in the current directory
        # does not alter the value of sys.path[0]
        with support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, 'other')
            with support.change_cwd(path=script_dir):
                with open("-m", "w") as f:
                    f.write("data")
                    rc, out, err = assert_python_ok('-m',
                                                    'other',
                                                    *example_args,
                                                    __isolated=False)
                    self._check_output(script_name, rc, out, script_name,
                                       script_name, script_dir, '',
                                       importlib.machinery.SourceFileLoader)

    def test_issue20884(self):
        # On Windows, script with encoding cookie and LF line ending
        # will be failed.
        with support.temp_dir() as script_dir:
            script_name = os.path.join(script_dir, "issue20884.py")
            with open(script_name, "w", newline='\n') as f:
                f.write("#coding: iso-8859-1\n")
                f.write('"""\n')
                for _ in range(30):
                    f.write('x' * 80 + '\n')
                f.write('"""\n')

            with support.change_cwd(path=script_dir):
                rc, out, err = assert_python_ok(script_name)
            self.assertEqual(b"", out)
            self.assertEqual(b"", err)

    @contextlib.contextmanager
    def setup_test_pkg(self, *args):
        with support.temp_dir() as script_dir, \
                support.change_cwd(path=script_dir):
            pkg_dir = os.path.join(script_dir, 'test_pkg')
            make_pkg(pkg_dir, *args)
            yield pkg_dir

    def check_dash_m_failure(self, *args):
        rc, out, err = assert_python_failure('-m', *args, __isolated=False)
        if verbose > 1:
            print(repr(out))
        self.assertEqual(rc, 1)
        return err

    def test_dash_m_error_code_is_one(self):
        # If a module is invoked with the -m command line flag
        # and results in an error that the return code to the
        # shell is '1'
        with self.setup_test_pkg() as pkg_dir:
            script_name = _make_test_script(
                pkg_dir, 'other',
                "if __name__ == '__main__': raise ValueError")
            err = self.check_dash_m_failure('test_pkg.other', *example_args)
            self.assertIn(b'ValueError', err)

    def test_dash_m_errors(self):
        # Exercise error reporting for various invalid package executions
        tests = (
            ('builtins', br'No code object available'),
            ('builtins.x', br'Error while finding module specification.*'
             br'ModuleNotFoundError'),
            ('builtins.x.y', br'Error while finding module specification.*'
             br'ModuleNotFoundError.*No module named.*not a package'),
            ('os.path', br'loader.*cannot handle'),
            ('importlib', br'No module named.*'
             br'is a package and cannot be directly executed'),
            ('importlib.nonexistent', br'No module named'),
            ('.unittest', br'Relative module names not supported'),
        )
        for name, regex in tests:
            with self.subTest(name):
                rc, _, err = assert_python_failure('-m', name)
                self.assertEqual(rc, 1)
                self.assertRegex(err, regex)
                self.assertNotIn(b'Traceback', err)

    def test_dash_m_bad_pyc(self):
        with support.temp_dir() as script_dir, \
                support.change_cwd(path=script_dir):
            os.mkdir('test_pkg')
            # Create invalid *.pyc as empty file
            with open('test_pkg/__init__.pyc', 'wb'):
                pass
            err = self.check_dash_m_failure('test_pkg')
            self.assertRegex(
                err, br'Error while finding module specification.*'
                br'ImportError.*bad magic number')
            self.assertNotIn(b'is a package', err)
            self.assertNotIn(b'Traceback', err)

    def test_dash_m_init_traceback(self):
        # These were wrapped in an ImportError and tracebacks were
        # suppressed; see Issue 14285
        exceptions = (ImportError, AttributeError, TypeError, ValueError)
        for exception in exceptions:
            exception = exception.__name__
            init = "raise {0}('Exception in __init__.py')".format(exception)
            with self.subTest(exception), \
                    self.setup_test_pkg(init) as pkg_dir:
                err = self.check_dash_m_failure('test_pkg')
                self.assertIn(exception.encode('ascii'), err)
                self.assertIn(b'Exception in __init__.py', err)
                self.assertIn(b'Traceback', err)

    def test_dash_m_main_traceback(self):
        # Ensure that an ImportError's traceback is reported
        with self.setup_test_pkg() as pkg_dir:
            main = "raise ImportError('Exception in __main__ module')"
            _make_test_script(pkg_dir, '__main__', main)
            err = self.check_dash_m_failure('test_pkg')
            self.assertIn(b'ImportError', err)
            self.assertIn(b'Exception in __main__ module', err)
            self.assertIn(b'Traceback', err)

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_pep_409_verbiage(self):
        # Make sure PEP 409 syntax properly suppresses
        # the context of an exception
        script = textwrap.dedent("""\
            try:
                raise ValueError
            except:
                raise NameError from None
            """)
        with support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, 'script', script)
            exitcode, stdout, stderr = assert_python_failure(script_name)
            text = stderr.decode('ascii').split('\n')
            self.assertEqual(len(text), 4)
            self.assertTrue(text[0].startswith('Traceback'))
            self.assertTrue(text[1].startswith('  File '))
            self.assertTrue(text[3].startswith('NameError'))

    def test_non_ascii(self):
        # Mac OS X denies the creation of a file with an invalid UTF-8 name.
        # Windows allows creating a name with an arbitrary bytes name, but
        # Python cannot a undecodable bytes argument to a subprocess.
        if (support.TESTFN_UNDECODABLE
                and sys.platform not in ('win32', 'darwin')):
            name = os.fsdecode(support.TESTFN_UNDECODABLE)
        elif support.TESTFN_NONASCII:
            name = support.TESTFN_NONASCII
        else:
            self.skipTest("need support.TESTFN_NONASCII")

        # Issue #16218
        source = 'print(ascii(__file__))\n'
        script_name = _make_test_script(os.curdir, name, source)
        self.addCleanup(support.unlink, script_name)
        rc, stdout, stderr = assert_python_ok(script_name)
        self.assertEqual(ascii(script_name),
                         stdout.rstrip().decode('ascii'),
                         'stdout=%r stderr=%r' % (stdout, stderr))
        self.assertEqual(0, rc)

    # TODO: RUSTPYTHON
    if sys.platform == "linux":
        test_non_ascii = unittest.expectedFailure(test_non_ascii)

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_issue20500_exit_with_exception_value(self):
        script = textwrap.dedent("""\
            import sys
            error = None
            try:
                raise ValueError('some text')
            except ValueError as err:
                error = err

            if error:
                sys.exit(error)
            """)
        with support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, 'script', script)
            exitcode, stdout, stderr = assert_python_failure(script_name)
            text = stderr.decode('ascii')
            self.assertEqual(text, "some text")

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_syntaxerror_unindented_caret_position(self):
        script = "1 + 1 = 2\n"
        with support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, 'script', script)
            exitcode, stdout, stderr = assert_python_failure(script_name)
            text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read()
            # Confirm that the caret is located under the first 1 character
            self.assertIn("\n    1 + 1 = 2\n    ^", text)

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_syntaxerror_indented_caret_position(self):
        script = textwrap.dedent("""\
            if True:
                1 + 1 = 2
            """)
        with support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, 'script', script)
            exitcode, stdout, stderr = assert_python_failure(script_name)
            text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read()
            # Confirm that the caret is located under the first 1 character
            self.assertIn("\n    1 + 1 = 2\n    ^", text)

            # Try the same with a form feed at the start of the indented line
            script = ("if True:\n" "\f    1 + 1 = 2\n")
            script_name = _make_test_script(script_dir, "script", script)
            exitcode, stdout, stderr = assert_python_failure(script_name)
            text = io.TextIOWrapper(io.BytesIO(stderr), "ascii").read()
            self.assertNotIn("\f", text)
            self.assertIn("\n    1 + 1 = 2\n    ^", text)

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_syntaxerror_multi_line_fstring(self):
        script = 'foo = f"""{}\nfoo"""\n'
        with support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, 'script', script)
            exitcode, stdout, stderr = assert_python_failure(script_name)
            self.assertEqual(
                stderr.splitlines()[-3:],
                [
                    b'    foo = f"""{}',
                    b'          ^',
                    b'SyntaxError: f-string: empty expression not allowed',
                ],
            )

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_syntaxerror_invalid_escape_sequence_multi_line(self):
        script = 'foo = """\\q\n"""\n'
        with support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, 'script', script)
            exitcode, stdout, stderr = assert_python_failure(
                '-Werror',
                script_name,
            )
            self.assertEqual(
                stderr.splitlines()[-3:],
                [
                    b'    foo = """\\q',
                    b'          ^',
                    b'SyntaxError: invalid escape sequence \\q',
                ],
            )

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_consistent_sys_path_for_direct_execution(self):
        # This test case ensures that the following all give the same
        # sys.path configuration:
        #
        #    ./python -s script_dir/__main__.py
        #    ./python -s script_dir
        #    ./python -I script_dir
        script = textwrap.dedent("""\
            import sys
            for entry in sys.path:
                print(entry)
            """)
        # Always show full path diffs on errors
        self.maxDiff = None
        with support.temp_dir() as work_dir, support.temp_dir() as script_dir:
            script_name = _make_test_script(script_dir, '__main__', script)
            # Reference output comes from directly executing __main__.py
            # We omit PYTHONPATH and user site to align with isolated mode
            p = spawn_python("-Es", script_name, cwd=work_dir)
            out_by_name = kill_python(p).decode().splitlines()
            self.assertEqual(out_by_name[0], script_dir)
            self.assertNotIn(work_dir, out_by_name)
            # Directory execution should give the same output
            p = spawn_python("-Es", script_dir, cwd=work_dir)
            out_by_dir = kill_python(p).decode().splitlines()
            self.assertEqual(out_by_dir, out_by_name)
            # As should directory execution in isolated mode
            p = spawn_python("-I", script_dir, cwd=work_dir)
            out_by_dir_isolated = kill_python(p).decode().splitlines()
            self.assertEqual(out_by_dir_isolated, out_by_dir, out_by_name)

    def test_consistent_sys_path_for_module_execution(self):
        # This test case ensures that the following both give the same
        # sys.path configuration:
        #    ./python -sm script_pkg.__main__
        #    ./python -sm script_pkg
        #
        # And that this fails as unable to find the package:
        #    ./python -Im script_pkg
        script = textwrap.dedent("""\
            import sys
            for entry in sys.path:
                print(entry)
            """)
        # Always show full path diffs on errors
        self.maxDiff = None
        with support.temp_dir() as work_dir:
            script_dir = os.path.join(work_dir, "script_pkg")
            os.mkdir(script_dir)
            script_name = _make_test_script(script_dir, '__main__', script)
            # Reference output comes from `-m script_pkg.__main__`
            # We omit PYTHONPATH and user site to better align with the
            # direct execution test cases
            p = spawn_python("-sm", "script_pkg.__main__", cwd=work_dir)
            out_by_module = kill_python(p).decode().splitlines()
            self.assertEqual(out_by_module[0], work_dir)
            self.assertNotIn(script_dir, out_by_module)
            # Package execution should give the same output
            p = spawn_python("-sm", "script_pkg", cwd=work_dir)
            out_by_package = kill_python(p).decode().splitlines()
            self.assertEqual(out_by_package, out_by_module)
            # Isolated mode should fail with an import error
            exitcode, stdout, stderr = assert_python_failure("-Im",
                                                             "script_pkg",
                                                             cwd=work_dir)
            traceback_lines = stderr.decode().splitlines()
            self.assertIn("No module named script_pkg", traceback_lines[-1])

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_nonexisting_script(self):
        # bpo-34783: "./python script.py" must not crash
        # if the script file doesn't exist.
        # (Skip test for macOS framework builds because sys.excutable name
        #  is not the actual Python executable file name.
        script = 'nonexistingscript.py'
        self.assertFalse(os.path.exists(script))

        proc = spawn_python(script,
                            text=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
        out, err = proc.communicate()
        self.assertIn(": can't open file ", err)
        self.assertNotEqual(proc.returncode, 0)
Exemplo n.º 40
0
class MemcacheTest(CacheClientTestMixIn, TestCase):
    is_lru = False
    capacity_means_entries = False
    meaningful_capacity = False  # controlled externally so it may not be consistent for testing purposes

    # Big uncompressible (but ascii-compatible) value
    BIG_VALUE = os.urandom(4 << 20).encode("base64")

    def setUpClient(self, **kwargs):
        from chorde.clients.memcached import MemcachedClient
        import threading
        rv = MemcachedClient([DEFAULT_CLIENT_ADDR],
                             checksum_key="test",
                             encoding_cache=threading.local(),
                             **kwargs)
        rv.client.flush_all()
        return rv

    def tearDown(self):
        # Manually clear memcached
        self.client.client.flush_all()

    def testSucceedFast(self):
        client = self.client
        val = "a" * 2
        client.put(4, val, 10)
        self.assertEqual(client.get(4, None), val)
        val = client.get(4, None)
        self.assertIs(client.get(4, None), val)

    def testStats(self):
        stats = self.client.stats
        self.assertIsNotNone(stats)
        self.assertIsInstance(stats, (dict, list, tuple))

    def testTupleKey(self):
        client = self.client
        client.put((1, 2), 2, 10)
        self.assertEqual(client.get((1, 2)), 2)

    def testStringKey(self):
        client = self.client
        k = "abracadabra"
        client.put(k, "patadecabra", 10)
        self.assertEqual(client.get(k), "patadecabra")

    def testLongStringKey(self):
        client = self.client
        k = "abracadabra"
        k = k * (
            getattr(self.client, 'max_backing_key_length', 2048) / len(k) + 1)
        client.put(k, "patadecabra2", 10)
        self.assertEqual(client.get(k), "patadecabra2")

    def testUTFStringKey(self):
        client = self.client
        k = u"ábracadíbra".encode("utf8")
        client.put(k, "patadecabra", 10)
        self.assertEqual(client.get(k), "patadecabra")

    def testLongUTFStringKey(self):
        client = self.client
        k = u"ábracadíbra".encode("utf8")
        k = k * (
            getattr(self.client, 'max_backing_key_length', 2048) / len(k) + 1)
        client.put(k, "patadecabra2", 10)
        self.assertEqual(client.get(k), "patadecabra2")

    def testUnicodeStringKey(self):
        client = self.client
        k = u"ábracadíbra"
        client.put(k, "patadecabra", 10)
        self.assertEqual(client.get(k), "patadecabra")

    def testLongUnicodeStringKey(self):
        client = self.client
        k = u"ábracadíbra"
        k = k * (
            getattr(self.client, 'max_backing_key_length', 2048) / len(k) + 1)
        client.put(k, "patadecabra2", 10)
        self.assertEqual(client.get(k), "patadecabra2")

    def testSpacedStringKey(self):
        client = self.client
        k = "abra cadabra"
        client.put(k, "patadecabra3", 10)
        self.assertEqual(client.get(k), "patadecabra3")

    def testSpacedLongStringKey(self):
        client = self.client
        k = "abra cadabra"
        k = k * (
            getattr(self.client, 'max_backing_key_length', 2048) / len(k) + 1)
        client.put(k, "patadecabra4", 10)
        self.assertEqual(client.get(k), "patadecabra4")

    def testObjectKey(self):
        client = self.client
        k = K()
        client.put(k, 15, 10)
        self.assertEqual(client.get(k), 15)

    def testNullKey(self):
        client = self.client
        client.put(None, 15, 10)
        self.assertEqual(client.get(None), 15)

    def testBigValue(self):
        bigval = self.BIG_VALUE
        client = self.client
        client.put("bigkey1", bigval, 60)
        self.assertEqual(client.get("bigkey1"), bigval)

    def testOverwriteBigValue(self):
        bigval = self.BIG_VALUE
        client = self.client
        if hasattr(client, 'shorten_key'):
            short_key, exact = client.shorten_key("bigkey2")
            client.put("bigkey2", bigval, 60)
            time.sleep(1)  # let it write
            old_index_page = client.client.get(short_key + "|0")
            old_page_prefix = client._page_prefix(old_index_page, short_key)
            client.put("bigkey2", bigval + "ENDMARK", 60)
            self.assertIsNone(client.client.get(old_page_prefix + "1"),
                              "Not expired")  # should have expired
            self.assertEqual(client.get("bigkey2"), bigval + "ENDMARK")

    def testRenewBigValue(self):
        bigval = self.BIG_VALUE
        client = self.client
        client.put("bigkey2", bigval, 10)
        client.renew("bigkey2", 120)
        self.assertGreater(client.getTtl("bigkey2")[1], 10)

    def testContainsBigValue(self):
        bigval = self.BIG_VALUE
        client = self.client
        client.put("bigkey3", bigval, 10)
        self.assertTrue(client.contains("bigkey3"))

    def testContainsBigValueTTLExact(self):
        bigval = self.BIG_VALUE
        client = self.client
        client.put("bigkey3", bigval, 100)
        self.assertTrue(client.contains("bigkey3", 50))

    def testContainsBigValueTTLInexact(self):
        bigval = self.BIG_VALUE
        client = self.client
        bigkey = "bigkey3" * 500
        client.put(bigkey, bigval, 100)

        # Force re-decoding
        if hasattr(client, 'encoding_cache'):
            client.encoding_cache.cache = None

        self.assertTrue(client.contains(bigkey, 50))

    def testTTLTooBig(self):
        from chorde.clients.memcached import MAX_MEMCACHE_TTL
        client = self.client
        k = "abra cadabra"
        client.put(k, "patadecabra3", MAX_MEMCACHE_TTL * 2)
        self.assertEqual(client.get(k), "patadecabra3")
        self.assertTrue(MAX_MEMCACHE_TTL * 2 -
                        1 <= client.getTtl(k)[1] <= MAX_MEMCACHE_TTL * 2)

    def testBigValueMissingFirstPage(self):
        bigval = self.BIG_VALUE
        client = self.client
        client.put("bigkey1", bigval, 60)
        shorten_key, _ = client.shorten_key('bigkey1')
        client.client.delete(shorten_key + '|0')

        with self.assertRaises(CacheMissError):
            client.get("bigkey1")

    def testBigValueMissingOnePage(self):
        bigval = self.BIG_VALUE
        client = self.client
        client.put("bigkey1", bigval, 60)
        shorten_key, _ = client.shorten_key('bigkey1')
        page = client.client.get(shorten_key + '|0')
        page_prefix = client._page_prefix(page, shorten_key)
        client.client.delete(page_prefix + '1')

        with self.assertRaises(CacheMissError):
            client.get("bigkey1")

    testClear = unittest.expectedFailure(CacheClientTestMixIn.testClear)
    testPurge = unittest.expectedFailure(CacheClientTestMixIn.testPurge)
Exemplo n.º 41
0
def load_tests(loader, standard_tests, pattern):
    if sys.implementation.name == 'ironpython':
        suite = unittest.TestSuite()
        suite.addTest(test.test_re.ExternalTests('test_re_benchmarks'))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ExternalTests('test_re_tests')))
        suite.addTest(test.test_re.ImplementationTest('test_overlap_table'))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.PatternReprTests('test_bytes')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.PatternReprTests('test_inline_flags')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.PatternReprTests('test_long_pattern')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.PatternReprTests('test_multiple_flags')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.PatternReprTests('test_quotes')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.PatternReprTests('test_single_flag')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.PatternReprTests('test_unicode_flag')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.PatternReprTests('test_unknown_flags')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.PatternReprTests('test_without_flags')))
        suite.addTest(test.test_re.ReTests('test_anyall'))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_ascii_and_unicode_flag')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_backref_group_name_in_exception')))
        suite.addTest(test.test_re.ReTests('test_basic_re_sub'))
        suite.addTest(test.test_re.ReTests('test_big_codesize'))
        suite.addTest(test.test_re.ReTests('test_bigcharset'))
        suite.addTest(test.test_re.ReTests('test_bug_113254'))
        suite.addTest(test.test_re.ReTests('test_bug_114660'))
        suite.addTest(test.test_re.ReTests('test_bug_117612'))
        suite.addTest(
            unittest.expectedFailure(test.test_re.ReTests('test_bug_13899')))
        suite.addTest(
            unittest.expectedFailure(test.test_re.ReTests('test_bug_1661')))
        suite.addTest(test.test_re.ReTests('test_bug_16688'))
        suite.addTest(test.test_re.ReTests('test_bug_20998'))
        suite.addTest(test.test_re.ReTests('test_bug_2537'))
        suite.addTest(test.test_re.ReTests('test_bug_3629'))
        suite.addTest(test.test_re.ReTests('test_bug_418626'))
        suite.addTest(test.test_re.ReTests('test_bug_448951'))
        suite.addTest(test.test_re.ReTests('test_bug_449000'))
        suite.addTest(test.test_re.ReTests('test_bug_449964'))
        suite.addTest(test.test_re.ReTests('test_bug_462270'))
        suite.addTest(test.test_re.ReTests('test_bug_527371'))
        suite.addTest(test.test_re.ReTests('test_bug_545855'))
        suite.addTest(
            unittest.expectedFailure(test.test_re.ReTests('test_bug_581080')))
        suite.addTest(test.test_re.ReTests('test_bug_612074'))
        suite.addTest(test.test_re.ReTests('test_bug_6509'))
        suite.addTest(test.test_re.ReTests('test_bug_6561'))
        suite.addTest(test.test_re.ReTests('test_bug_725106'))
        suite.addTest(test.test_re.ReTests('test_bug_725149'))
        suite.addTest(
            unittest.expectedFailure(test.test_re.ReTests('test_bug_764548')))
        suite.addTest(test.test_re.ReTests('test_bug_817234'))
        suite.addTest(test.test_re.ReTests('test_bug_926075'))
        suite.addTest(test.test_re.ReTests('test_bug_931848'))
        suite.addTest(test.test_re.ReTests('test_bytes_str_mixing'))
        suite.addTest(test.test_re.ReTests('test_category'))
        suite.addTest(
            unittest.expectedFailure(test.test_re.ReTests('test_compile')))
        suite.addTest(test.test_re.ReTests('test_constants'))
        suite.addTest(
            unittest.expectedFailure(test.test_re.ReTests('test_dealloc')))
        suite.addTest(
            unittest.expectedFailure(test.test_re.ReTests('test_debug_flag')))
        suite.addTest(test.test_re.ReTests('test_dollar_matches_twice'))
        suite.addTest(test.test_re.ReTests('test_empty_array'))
        suite.addTest(test.test_re.ReTests('test_expand'))
        suite.addTest(test.test_re.ReTests('test_finditer'))
        suite.addTest(test.test_re.ReTests('test_flags'))
        suite.addTest(test.test_re.ReTests('test_getattr'))
        suite.addTest(test.test_re.ReTests('test_getlower'))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_group_name_in_exception')))
        suite.addTest(test.test_re.ReTests('test_groupdict'))
        suite.addTest(
            unittest.expectedFailure(test.test_re.ReTests('test_ignore_case')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_ignore_case_range')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_ignore_case_set')))
        suite.addTest(test.test_re.ReTests('test_inline_flags'))
        suite.addTest(test.test_re.ReTests('test_issue17998'))
        suite.addTest(
            unittest.expectedFailure(test.test_re.ReTests('test_keep_buffer')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_keyword_parameters')))
        suite.addTest(test.test_re.ReTests('test_large_search'))
        suite.addTest(test.test_re.ReTests('test_large_subn'))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests(
                    'test_locale_caching')))  # fails on .NET Core linux/macos
        suite.addTest(test.test_re.ReTests('test_lookahead'))
        suite.addTest(
            unittest.expectedFailure(test.test_re.ReTests('test_lookbehind')))
        suite.addTest(
            unittest.expectedFailure(test.test_re.ReTests('test_match_repr')))
        suite.addTest(test.test_re.ReTests('test_not_literal'))
        suite.addTest(
            unittest.expectedFailure(test.test_re.ReTests('test_pickling')))
        suite.addTest(test.test_re.ReTests('test_qualified_re_split'))
        suite.addTest(test.test_re.ReTests('test_qualified_re_sub'))
        suite.addTest(
            unittest.expectedFailure(test.test_re.ReTests('test_re_escape')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_re_escape_byte')))
        suite.addTest(test.test_re.ReTests('test_re_escape_non_ascii'))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_re_escape_non_ascii_bytes')))
        suite.addTest(test.test_re.ReTests('test_re_findall'))
        suite.addTest(test.test_re.ReTests('test_re_fullmatch'))
        suite.addTest(test.test_re.ReTests('test_re_groupref'))
        suite.addTest(test.test_re.ReTests('test_re_groupref_exists'))
        suite.addTest(test.test_re.ReTests('test_re_match'))
        suite.addTest(test.test_re.ReTests('test_re_split'))
        suite.addTest(test.test_re.ReTests('test_re_subn'))
        suite.addTest(test.test_re.ReTests('test_repeat_minmax'))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_repeat_minmax_overflow')))
        suite.addTest(
            test.test_re.ReTests('test_repeat_minmax_overflow_maxrepeat'))
        suite.addTest(test.test_re.ReTests('test_scanner'))
        suite.addTest(test.test_re.ReTests('test_search_coverage'))
        suite.addTest(test.test_re.ReTests('test_search_dot_unicode'))
        suite.addTest(test.test_re.ReTests('test_search_star_plus'))
        suite.addTest(test.test_re.ReTests('test_special_escapes'))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_sre_byte_class_literals')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_sre_byte_literals')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_sre_character_class_literals')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_sre_character_literals')))
        suite.addTest(test.test_re.ReTests('test_stack_overflow'))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_string_boundaries')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_sub_template_numeric_escape')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_symbolic_groups')))
        suite.addTest(
            unittest.expectedFailure(
                test.test_re.ReTests('test_symbolic_refs')))
        suite.addTest(test.test_re.ReTests('test_unlimited_zero_width_repeat'))
        suite.addTest(test.test_re.ReTests('test_weakref'))
        return suite

    else:
        return loader.loadTestsFromModule(test.test_re, pattern)
Exemplo n.º 42
0
        obj.save()

    # Assert that the deserialized data is the same
    # as the original source
    for (func, pk, klass, datum) in test_data:
        func[1](self, pk, klass, datum)

    # Assert that the number of objects deserialized is the
    # same as the number that was serialized.
    for klass, count in instance_count.items():
        self.assertEqual(count, klass.objects.count())


if connection.vendor == 'mysql' and six.PY3:
    # Existing MySQL DB-API drivers fail on binary data.
    serializerTest = expectedFailure(serializerTest)


def naturalKeySerializerTest(format, self):
    # Create all the objects defined in the test data
    objects = []
    instance_count = {}
    for (func, pk, klass, datum) in natural_key_test_data:
        with connection.constraint_checks_disabled():
            objects.extend(func[0](pk, klass, datum))

    # Get a count of the number of objects created for each class
    for klass in instance_count:
        instance_count[klass] = klass.objects.count()

    # use_natural_keys is deprecated and to be removed in Django 1.9
Exemplo n.º 43
0
 def f(func):
     if not is_module_available(module_name):
         return unittest.expectedFailure(func)
     return func
Exemplo n.º 44
0
 def wrap(fn):
     if xfail:
         return unittest.expectedFailure(fn)
     else:
         return fn
Exemplo n.º 45
0
    'PropertyAssignmentMovementGroup', 'PropertyMovementGroup',
    'QuantitySignMovementGroup', 'RequirementMovementGroup',
    'RootAppliedRuleCausalityMovementGroup', 'SplitMovementGroup',
    'TitleMovementGroup',
    'VariantMovementGroup', 'VariationPropertyMovementGroup']:
  implements_tuple_list.append((('Products.ERP5Type.Document.%s' % \
      movement_group_class_name, movement_group_class_name),
      'IMovementGroup'))

class TestERP5Interfaces(ERP5TypeTestCase):
  """Tests implementation of interfaces"""

addTestMethodDynamically(TestERP5Interfaces, implements_tuple_list)

for failing_method in [
    'test_Products.ERP5.AggregatedAmountList_AggregatedAmountList_implements_IAmountList',
    'test_Products.ERP5.Document.BusinessLink_BusinessLink_implements_IBusinessLink',
    'test_Products.ERP5.Document.BusinessLink_BusinessLink_implements_ICategoryAccessProvider',
    'test_Products.ERP5.Document.TradeModelCell_TradeModelCell_implements_IVariated',
    'test_Products.ERP5.Document.TradeModelLine_TradeModelLine_implements_IVariated',
    'test_Products.ERP5.Document.Transformation_Transformation_implements_IVariated',
    'test_Products.ERP5.Document.TransformedResource_TransformedResource_implements_IVariated',
  ]:
  setattr(TestERP5Interfaces, failing_method,
      expectedFailure(getattr(TestERP5Interfaces,failing_method)))

def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestERP5Interfaces))
  return suite
Exemplo n.º 46
0
        thread.start()

        time.sleep(0.1)
        canceller.cancel()
        thread.join()

        # This test should actually produce a time extremely close to the sleep duration ( within
        # 0.003 seconds whether the sleep duration is 0.01 seconds or 100 seconds ), but checking
        # that it terminates with 0.1 seconds is a minimal performance bar
        self.assertLess(time.time() - startTime, 0.2)
        self.assertTrue(cancelled[0])

    def setUp(self):

        os.environ[
            "CORTEX_POINTDISTRIBUTION_TILESET"] = "test/IECore/data/pointDistributions/pointDistributionTileSet2048.dat"


if sys.platform == "darwin":

    # These fail because MacOS uses libc++, and libc++ has a
    # different `std::random_shuffle()` than libstdc++.

    MeshAlgoDistributePointsTest.testDensityMaskPrimVar = unittest.expectedFailure(
        MeshAlgoDistributePointsTest.testDensityMaskPrimVar)
    MeshAlgoDistributePointsTest.testDistanceBetweenPoints = unittest.expectedFailure(
        MeshAlgoDistributePointsTest.testDistanceBetweenPoints)

if __name__ == "__main__":
    unittest.main()
Exemplo n.º 47
0
    def testSerialisation(self):

        s = Gaffer.ScriptNode()
        s["shader"] = GafferScene.OpenGLShader()
        s["shader"].loadShader("Constant")

        self.assertEqual(s["shader"].attributes()["gl:surface"][0].name,
                         "Constant")

        s2 = Gaffer.ScriptNode()
        s2.execute(s.serialise())

        self.assertEqual(s2["shader"].attributes(), s["shader"].attributes())


if sys.platform == "darwin":
    # The Texture shader used in the test provides only a .frag file, which
    # means that it gets the default vertex shader. The default vertex shader
    # declares a "Cs" parameter which for some reason the OSX shader compiler
    # fails to optimise out (it is not used in the fragment shader, so it should
    # be). This means we end up with an unexpected shader parameter and the test
    # fails. Since the issue is in the shader compiler itself, it seems there's
    # not much we can do (other than provide a .vert shader with the unnecessary
    # bit omitted), so for now we mark the test as an expected failure.
    OpenGLShaderTest.test = unittest.expectedFailure(OpenGLShaderTest.test)
    OpenGLShaderTest.testLoadShader = unittest.expectedFailure(
        OpenGLShaderTest.testLoadShader)

if __name__ == "__main__":
    unittest.main()
Exemplo n.º 48
0
class GeoLookupTest(TestCase):
    fixtures = ['initial']

    def test_disjoint_lookup(self):
        "Testing the `disjoint` lookup type."
        ptown = City.objects.get(name='Pueblo')
        qs1 = City.objects.filter(point__disjoint=ptown.point)
        self.assertEqual(7, qs1.count())

        if connection.features.supports_real_shape_operations:
            qs2 = State.objects.filter(poly__disjoint=ptown.point)
            self.assertEqual(1, qs2.count())
            self.assertEqual('Kansas', qs2[0].name)

    def test_contains_contained_lookups(self):
        "Testing the 'contained', 'contains', and 'bbcontains' lookup types."
        # Getting Texas, yes we were a country -- once ;)
        texas = Country.objects.get(name='Texas')

        # Seeing what cities are in Texas, should get Houston and Dallas,
        #  and Oklahoma City because 'contained' only checks on the
        #  _bounding box_ of the Geometries.
        if connection.features.supports_contained_lookup:
            qs = City.objects.filter(point__contained=texas.mpoly)
            self.assertEqual(3, qs.count())
            cities = ['Houston', 'Dallas', 'Oklahoma City']
            for c in qs:
                self.assertEqual(True, c.name in cities)

        # Pulling out some cities.
        houston = City.objects.get(name='Houston')
        wellington = City.objects.get(name='Wellington')
        pueblo = City.objects.get(name='Pueblo')
        okcity = City.objects.get(name='Oklahoma City')
        lawrence = City.objects.get(name='Lawrence')

        # Now testing contains on the countries using the points for
        #  Houston and Wellington.
        tx = Country.objects.get(mpoly__contains=houston.point)  # Query w/GEOSGeometry
        nz = Country.objects.get(mpoly__contains=wellington.point.hex)  # Query w/EWKBHEX
        self.assertEqual('Texas', tx.name)
        self.assertEqual('New Zealand', nz.name)

        # Spatialite 2.3 thinks that Lawrence is in Puerto Rico (a NULL geometry).
        if not (spatialite and connection.ops.spatial_version < 3):
            ks = State.objects.get(poly__contains=lawrence.point)
            self.assertEqual('Kansas', ks.name)

        # Pueblo and Oklahoma City (even though OK City is within the bounding box of Texas)
        # are not contained in Texas or New Zealand.
        self.assertEqual(len(Country.objects.filter(mpoly__contains=pueblo.point)), 0)  # Query w/GEOSGeometry object
        self.assertEqual(len(Country.objects.filter(mpoly__contains=okcity.point.wkt)),
                         0 if connection.features.supports_real_shape_operations else 1)  # Query w/WKT

        # OK City is contained w/in bounding box of Texas.
        if connection.features.supports_bbcontains_lookup:
            qs = Country.objects.filter(mpoly__bbcontains=okcity.point)
            self.assertEqual(1, len(qs))
            self.assertEqual('Texas', qs[0].name)

    @skipUnlessDBFeature("supports_left_right_lookups")
    def test_left_right_lookups(self):
        "Testing the 'left' and 'right' lookup types."
        # Left: A << B => true if xmax(A) < xmin(B)
        # Right: A >> B => true if xmin(A) > xmax(B)
        # See: BOX2D_left() and BOX2D_right() in lwgeom_box2dfloat4.c in PostGIS source.

        # Getting the borders for Colorado & Kansas
        co_border = State.objects.get(name='Colorado').poly
        ks_border = State.objects.get(name='Kansas').poly

        # Note: Wellington has an 'X' value of 174, so it will not be considered
        # to the left of CO.

        # These cities should be strictly to the right of the CO border.
        cities = ['Houston', 'Dallas', 'Oklahoma City',
                  'Lawrence', 'Chicago', 'Wellington']
        qs = City.objects.filter(point__right=co_border)
        self.assertEqual(6, len(qs))
        for c in qs:
            self.assertEqual(True, c.name in cities)

        # These cities should be strictly to the right of the KS border.
        cities = ['Chicago', 'Wellington']
        qs = City.objects.filter(point__right=ks_border)
        self.assertEqual(2, len(qs))
        for c in qs:
            self.assertEqual(True, c.name in cities)

        # Note: Wellington has an 'X' value of 174, so it will not be considered
        #  to the left of CO.
        vic = City.objects.get(point__left=co_border)
        self.assertEqual('Victoria', vic.name)

        cities = ['Pueblo', 'Victoria']
        qs = City.objects.filter(point__left=ks_border)
        self.assertEqual(2, len(qs))
        for c in qs:
            self.assertEqual(True, c.name in cities)

    # The left/right lookup tests are known failures on PostGIS 2.0/2.0.1
    # http://trac.osgeo.org/postgis/ticket/2035
    if postgis_bug_version():
        test_left_right_lookups = unittest.expectedFailure(test_left_right_lookups)

    def test_equals_lookups(self):
        "Testing the 'same_as' and 'equals' lookup types."
        pnt = fromstr('POINT (-95.363151 29.763374)', srid=4326)
        c1 = City.objects.get(point=pnt)
        c2 = City.objects.get(point__same_as=pnt)
        c3 = City.objects.get(point__equals=pnt)
        for c in [c1, c2, c3]:
            self.assertEqual('Houston', c.name)

    @skipUnlessDBFeature("supports_null_geometries")
    def test_null_geometries(self):
        "Testing NULL geometry support, and the `isnull` lookup type."
        # Creating a state with a NULL boundary.
        State.objects.create(name='Puerto Rico')

        # Querying for both NULL and Non-NULL values.
        nullqs = State.objects.filter(poly__isnull=True)
        validqs = State.objects.filter(poly__isnull=False)

        # Puerto Rico should be NULL (it's a commonwealth unincorporated territory)
        self.assertEqual(1, len(nullqs))
        self.assertEqual('Puerto Rico', nullqs[0].name)

        # The valid states should be Colorado & Kansas
        self.assertEqual(2, len(validqs))
        state_names = [s.name for s in validqs]
        self.assertEqual(True, 'Colorado' in state_names)
        self.assertEqual(True, 'Kansas' in state_names)

        # Saving another commonwealth w/a NULL geometry.
        nmi = State.objects.create(name='Northern Mariana Islands', poly=None)
        self.assertEqual(nmi.poly, None)

        # Assigning a geometry and saving -- then UPDATE back to NULL.
        nmi.poly = 'POLYGON((0 0,1 0,1 1,1 0,0 0))'
        nmi.save()
        State.objects.filter(name='Northern Mariana Islands').update(poly=None)
        self.assertEqual(None, State.objects.get(name='Northern Mariana Islands').poly)

    @skipUnlessDBFeature("supports_relate_lookup")
    def test_relate_lookup(self):
        "Testing the 'relate' lookup type."
        # To make things more interesting, we will have our Texas reference point in
        # different SRIDs.
        pnt1 = fromstr('POINT (649287.0363174 4177429.4494686)', srid=2847)
        pnt2 = fromstr('POINT(-98.4919715741052 29.4333344025053)', srid=4326)

        # Not passing in a geometry as first param should
        # raise a type error when initializing the GeoQuerySet
        self.assertRaises(ValueError, Country.objects.filter, mpoly__relate=(23, 'foo'))

        # Making sure the right exception is raised for the given
        # bad arguments.
        for bad_args, e in [((pnt1, 0), ValueError), ((pnt2, 'T*T***FF*', 0), ValueError)]:
            qs = Country.objects.filter(mpoly__relate=bad_args)
            self.assertRaises(e, qs.count)

        # Relate works differently for the different backends.
        if postgis or spatialite:
            contains_mask = 'T*T***FF*'
            within_mask = 'T*F**F***'
            intersects_mask = 'T********'
        elif oracle:
            contains_mask = 'contains'
            within_mask = 'inside'
            # TODO: This is not quite the same as the PostGIS mask above
            intersects_mask = 'overlapbdyintersect'

        # Testing contains relation mask.
        self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt1, contains_mask)).name)
        self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt2, contains_mask)).name)

        # Testing within relation mask.
        ks = State.objects.get(name='Kansas')
        self.assertEqual('Lawrence', City.objects.get(point__relate=(ks.poly, within_mask)).name)

        # Testing intersection relation mask.
        if not oracle:
            self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt1, intersects_mask)).name)
            self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt2, intersects_mask)).name)
            self.assertEqual('Lawrence', City.objects.get(point__relate=(ks.poly, intersects_mask)).name)
Exemplo n.º 49
0
    return test


def _artemis_runner(name, path):
    return execute_artemis(
        name,
        path,
        iterations=0,
        debug_concolic=" ",
        major_mode="concolic",
        concolic_event_sequences="simple",
        # concolic_search_procedure='dfs-testing',
        verbose=True,
    )


if __name__ == "__main__":

    for t in list_tests_in_folder(FIXTURE_ROOT):
        test_name = "test_%s" % t["fn"].replace(".", "_")
        file_name = "%s%s" % (FIXTURE_ROOT, t["fn"])

        test = test_generator(_artemis_runner, file_name, test_name, test_dict=t["test"], internal_test=t["i_test"])
        if t["expected_failure"]:
            test = unittest.expectedFailure(test)

        setattr(Concolic, test_name, test)

    unittest.main(buffer=True, catchbreak=True)
Exemplo n.º 50
0
def load_tests(loader, standard_tests, pattern):
    if sys.implementation.name == 'ironpython':
        suite = unittest.TestSuite()
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.Oddballs('test_bug_1028306')))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDate('test_backdoor_resistance')))
        suite.addTest(
            test.datetimetester.TestDate('test_bad_constructor_arguments'))
        suite.addTest(test.datetimetester.TestDate('test_basic_attributes'))
        suite.addTest(test.datetimetester.TestDate('test_bool'))
        suite.addTest(test.datetimetester.TestDate('test_compare'))
        suite.addTest(test.datetimetester.TestDate('test_computations'))
        suite.addTest(test.datetimetester.TestDate('test_ctime'))
        suite.addTest(test.datetimetester.TestDate('test_extreme_ordinals'))
        suite.addTest(test.datetimetester.TestDate('test_extreme_timedelta'))
        suite.addTest(test.datetimetester.TestDate('test_format'))
        suite.addTest(test.datetimetester.TestDate('test_fromtimestamp'))
        suite.addTest(
            test.datetimetester.TestDate('test_harmful_mixed_comparison'))
        suite.addTest(
            test.datetimetester.TestDate('test_harmless_mixed_comparison'))
        suite.addTest(test.datetimetester.TestDate('test_hash_equality'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDate('test_insane_fromtimestamp')))
        suite.addTest(test.datetimetester.TestDate('test_iso_long_years'))
        suite.addTest(test.datetimetester.TestDate('test_isocalendar'))
        suite.addTest(test.datetimetester.TestDate('test_isoformat'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDate('test_mixed_compare')))
        suite.addTest(test.datetimetester.TestDate('test_ordinal_conversions'))
        suite.addTest(test.datetimetester.TestDate('test_overflow'))
        suite.addTest(test.datetimetester.TestDate('test_pickling'))
        suite.addTest(
            test.datetimetester.TestDate('test_pickling_subclass_date'))
        suite.addTest(test.datetimetester.TestDate('test_replace'))
        suite.addTest(test.datetimetester.TestDate('test_resolution_info'))
        suite.addTest(test.datetimetester.TestDate('test_roundtrip'))
        suite.addTest(test.datetimetester.TestDate('test_strftime'))
        suite.addTest(test.datetimetester.TestDate('test_strftime_y2k'))
        suite.addTest(test.datetimetester.TestDate('test_subclass_date'))
        suite.addTest(test.datetimetester.TestDate('test_timetuple'))
        suite.addTest(test.datetimetester.TestDate('test_today'))
        suite.addTest(test.datetimetester.TestDate('test_weekday'))
        suite.addTest(
            test.datetimetester.TestDateOnly('test_delta_non_days_ignored'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTime('test_astimezone'))
        )  # https://github.com/IronLanguages/ironpython3/issues/1136
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTime('test_backdoor_resistance')))
        suite.addTest(
            test.datetimetester.TestDateTime('test_bad_constructor_arguments'))
        suite.addTest(
            test.datetimetester.TestDateTime('test_basic_attributes'))
        suite.addTest(
            test.datetimetester.TestDateTime('test_basic_attributes_nonzero'))
        suite.addTest(test.datetimetester.TestDateTime('test_bool'))
        suite.addTest(test.datetimetester.TestDateTime('test_combine'))
        suite.addTest(test.datetimetester.TestDateTime('test_compare'))
        suite.addTest(test.datetimetester.TestDateTime('test_computations'))
        suite.addTest(test.datetimetester.TestDateTime('test_ctime'))
        suite.addTest(test.datetimetester.TestDateTime('test_extract'))
        suite.addTest(
            test.datetimetester.TestDateTime('test_extreme_ordinals'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTime('test_extreme_timedelta')))
        suite.addTest(test.datetimetester.TestDateTime('test_format'))
        suite.addTest(test.datetimetester.TestDateTime('test_fromtimestamp'))
        suite.addTest(
            test.datetimetester.TestDateTime('test_harmful_mixed_comparison'))
        suite.addTest(
            test.datetimetester.TestDateTime('test_harmless_mixed_comparison'))
        suite.addTest(test.datetimetester.TestDateTime('test_hash_equality'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTime('test_insane_fromtimestamp')))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTime(
                    'test_insane_utcfromtimestamp')))
        suite.addTest(test.datetimetester.TestDateTime('test_iso_long_years'))
        suite.addTest(test.datetimetester.TestDateTime('test_isocalendar'))
        suite.addTest(test.datetimetester.TestDateTime('test_isoformat'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTime('test_microsecond_rounding')))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTime('test_mixed_compare')))
        suite.addTest(test.datetimetester.TestDateTime('test_more_compare'))
        suite.addTest(test.datetimetester.TestDateTime('test_more_ctime'))
        suite.addTest(test.datetimetester.TestDateTime('test_more_pickling'))
        suite.addTest(test.datetimetester.TestDateTime('test_more_strftime'))
        suite.addTest(test.datetimetester.TestDateTime('test_more_timetuple'))
        suite.addTest(
            test.datetimetester.TestDateTime(
                'test_negative_float_fromtimestamp'))
        suite.addTest(
            test.datetimetester.TestDateTime(
                'test_negative_float_utcfromtimestamp'))
        suite.addTest(
            test.datetimetester.TestDateTime('test_ordinal_conversions'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTime('test_overflow')))
        suite.addTest(test.datetimetester.TestDateTime('test_pickling'))
        suite.addTest(
            test.datetimetester.TestDateTime('test_pickling_subclass_date'))
        suite.addTest(
            test.datetimetester.TestDateTime(
                'test_pickling_subclass_datetime'))
        suite.addTest(test.datetimetester.TestDateTime('test_replace'))
        suite.addTest(test.datetimetester.TestDateTime('test_resolution_info'))
        suite.addTest(test.datetimetester.TestDateTime('test_roundtrip'))
        suite.addTest(test.datetimetester.TestDateTime('test_strftime'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTime(
                    'test_strftime_with_bad_tzname_replace')))
        suite.addTest(test.datetimetester.TestDateTime('test_strftime_y2k'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTime('test_strptime')))
        suite.addTest(test.datetimetester.TestDateTime('test_subclass_date'))
        suite.addTest(
            test.datetimetester.TestDateTime('test_subclass_datetime'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTime('test_timestamp_aware'))
        )  # AttributeError: 'datetime' object has no attribute 'timestamp'
        suite.addTest(test.datetimetester.TestDateTime('test_timestamp_naive'))
        suite.addTest(test.datetimetester.TestDateTime('test_timetuple'))
        suite.addTest(test.datetimetester.TestDateTime('test_today'))
        suite.addTest(
            test.datetimetester.TestDateTime('test_tz_independent_comparing'))
        suite.addTest(
            test.datetimetester.TestDateTime('test_utcfromtimestamp'))
        suite.addTest(test.datetimetester.TestDateTime('test_utcnow'))
        suite.addTest(test.datetimetester.TestDateTime('test_weekday'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_argument_passing'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTimeTZ('test_astimezone'))
        )  # https://github.com/IronLanguages/ironpython3/issues/1136
        suite.addTest(
            test.datetimetester.TestDateTimeTZ(
                'test_astimezone_default_eastern'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_astimezone_default_utc'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_aware_compare'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_aware_subtract'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTimeTZ(
                    'test_backdoor_resistance')))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ(
                'test_bad_constructor_arguments'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_bad_tzinfo_classes'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_basic_attributes'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ(
                'test_basic_attributes_nonzero'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_bool'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_combine'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_compare'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_computations'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_ctime'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTimeTZ('test_even_more_compare')))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_extract'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTimeTZ('test_extreme_hashes')))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_extreme_ordinals'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTimeTZ('test_extreme_timedelta')))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_format'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_fromtimestamp'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ(
                'test_harmful_mixed_comparison'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ(
                'test_harmless_mixed_comparison'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_hash_equality'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTimeTZ(
                    'test_insane_fromtimestamp')))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTimeTZ(
                    'test_insane_utcfromtimestamp')))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_iso_long_years'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_isocalendar'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_isoformat'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTimeTZ(
                    'test_microsecond_rounding')))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTimeTZ('test_mixed_compare')))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_more_astimezone'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_more_compare'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_more_ctime'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_more_pickling'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_more_strftime'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_more_timetuple'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ(
                'test_negative_float_fromtimestamp'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ(
                'test_negative_float_utcfromtimestamp'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_ordinal_conversions'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTimeTZ('test_overflow')))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_pickling'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_pickling_subclass_date'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ(
                'test_pickling_subclass_datetime'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_replace'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_resolution_info'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_roundtrip'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_strftime'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTimeTZ(
                    'test_strftime_with_bad_tzname_replace')))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_strftime_y2k'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTimeTZ('test_strptime')))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_subclass_date'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_subclass_datetime'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_subclass_datetimetz'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTimeTZ('test_timestamp_aware'))
        )  # AttributeError: 'datetime' object has no attribute 'timestamp'
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_timestamp_naive'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_timetuple'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_today'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_trivial'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTimeTZ(
                    'test_tz_aware_arithmetic')))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ(
                'test_tz_independent_comparing'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_tzinfo_classes'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_tzinfo_fromtimestamp'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_tzinfo_isoformat'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_tzinfo_now'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_tzinfo_timetuple'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_tzinfo_utcfromtimestamp'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_tzinfo_utcnow'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ(
                'test_utc_offset_out_of_bounds'))
        suite.addTest(
            test.datetimetester.TestDateTimeTZ('test_utcfromtimestamp'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_utcnow'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestDateTimeTZ('test_utctimetuple'))
        )  # SystemError: Object reference not set to an instance of an object.
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_weekday'))
        suite.addTest(test.datetimetester.TestDateTimeTZ('test_zones'))
        suite.addTest(test.datetimetester.TestModule('test_constants'))
        suite.addTest(test.datetimetester.TestModule('test_divide_and_round'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestSubclassDateTime('test_astimezone'))
        )  # https://github.com/IronLanguages/ironpython3/issues/1136
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestSubclassDateTime(
                    'test_backdoor_resistance')))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime(
                'test_bad_constructor_arguments'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_basic_attributes'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime(
                'test_basic_attributes_nonzero'))
        suite.addTest(test.datetimetester.TestSubclassDateTime('test_bool'))
        suite.addTest(test.datetimetester.TestSubclassDateTime('test_combine'))
        suite.addTest(test.datetimetester.TestSubclassDateTime('test_compare'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_computations'))
        suite.addTest(test.datetimetester.TestSubclassDateTime('test_ctime'))
        suite.addTest(test.datetimetester.TestSubclassDateTime('test_extract'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_extreme_ordinals'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestSubclassDateTime(
                    'test_extreme_timedelta')))
        suite.addTest(test.datetimetester.TestSubclassDateTime('test_format'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_fromtimestamp'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime(
                'test_harmful_mixed_comparison'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime(
                'test_harmless_mixed_comparison'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_hash_equality'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestSubclassDateTime(
                    'test_insane_fromtimestamp')))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestSubclassDateTime(
                    'test_insane_utcfromtimestamp')))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_iso_long_years'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_isocalendar'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_isoformat'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestSubclassDateTime(
                    'test_microsecond_rounding')))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestSubclassDateTime(
                    'test_mixed_compare')))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_more_compare'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_more_ctime'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_more_pickling'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_more_strftime'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_more_timetuple'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime(
                'test_negative_float_fromtimestamp'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime(
                'test_negative_float_utcfromtimestamp'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime(
                'test_ordinal_conversions'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestSubclassDateTime('test_overflow')))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_pickling'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime(
                'test_pickling_subclass_date'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime(
                'test_pickling_subclass_datetime'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestSubclassDateTime(
                    'test_replace')))  # TODO
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_resolution_info'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_roundtrip'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_strftime'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestSubclassDateTime(
                    'test_strftime_with_bad_tzname_replace')))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_strftime_y2k'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestSubclassDateTime('test_strptime')))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_subclass_date'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_subclass_datetime'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestSubclassDateTime(
                    'test_timestamp_aware')))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_timestamp_naive'))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_timetuple'))
        suite.addTest(test.datetimetester.TestSubclassDateTime('test_today'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestSubclassDateTime(
                    'test_tz_independent_comparing')))
        suite.addTest(
            test.datetimetester.TestSubclassDateTime('test_utcfromtimestamp'))
        suite.addTest(test.datetimetester.TestSubclassDateTime('test_utcnow'))
        suite.addTest(test.datetimetester.TestSubclassDateTime('test_weekday'))
        suite.addTest(test.datetimetester.TestTZInfo('test_issue23600'))
        suite.addTest(test.datetimetester.TestTZInfo('test_non_abstractness'))
        suite.addTest(test.datetimetester.TestTZInfo('test_normal'))
        suite.addTest(test.datetimetester.TestTZInfo('test_pickling_base'))
        suite.addTest(test.datetimetester.TestTZInfo('test_pickling_subclass'))
        suite.addTest(
            test.datetimetester.TestTZInfo('test_refcnt_crash_bug_22044'))
        suite.addTest(
            test.datetimetester.TestTZInfo('test_subclass_must_override'))
        suite.addTest(test.datetimetester.TestTime('test_1653736'))
        suite.addTest(test.datetimetester.TestTime('test_backdoor_resistance'))
        suite.addTest(
            test.datetimetester.TestTime('test_bad_constructor_arguments'))
        suite.addTest(test.datetimetester.TestTime('test_basic_attributes'))
        suite.addTest(
            test.datetimetester.TestTime('test_basic_attributes_nonzero'))
        suite.addTest(test.datetimetester.TestTime('test_bool'))
        suite.addTest(test.datetimetester.TestTime('test_comparing'))
        suite.addTest(test.datetimetester.TestTime('test_format'))
        suite.addTest(
            test.datetimetester.TestTime('test_harmful_mixed_comparison'))
        suite.addTest(
            test.datetimetester.TestTime('test_harmless_mixed_comparison'))
        suite.addTest(test.datetimetester.TestTime('test_hash_equality'))
        suite.addTest(test.datetimetester.TestTime('test_isoformat'))
        suite.addTest(test.datetimetester.TestTime('test_pickling'))
        suite.addTest(
            test.datetimetester.TestTime('test_pickling_subclass_time'))
        suite.addTest(test.datetimetester.TestTime('test_replace'))
        suite.addTest(test.datetimetester.TestTime('test_repr'))
        suite.addTest(test.datetimetester.TestTime('test_resolution_info'))
        suite.addTest(test.datetimetester.TestTime('test_roundtrip'))
        suite.addTest(test.datetimetester.TestTime('test_str'))
        suite.addTest(test.datetimetester.TestTime('test_strftime'))
        suite.addTest(test.datetimetester.TestTime('test_subclass_time'))
        suite.addTest(
            test.datetimetester.TestTimeDelta('test_basic_attributes'))
        suite.addTest(test.datetimetester.TestTimeDelta('test_bool'))
        suite.addTest(test.datetimetester.TestTimeDelta('test_carries'))
        suite.addTest(test.datetimetester.TestTimeDelta('test_compare'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestTimeDelta(
                    'test_computations')))  # rounding differences
        suite.addTest(test.datetimetester.TestTimeDelta('test_constructor'))
        suite.addTest(
            test.datetimetester.TestTimeDelta('test_disallowed_computations'))
        suite.addTest(
            test.datetimetester.TestTimeDelta('test_disallowed_special'))
        suite.addTest(test.datetimetester.TestTimeDelta('test_division'))
        suite.addTest(test.datetimetester.TestTimeDelta('test_divmod'))
        suite.addTest(
            test.datetimetester.TestTimeDelta('test_harmful_mixed_comparison'))
        suite.addTest(
            test.datetimetester.TestTimeDelta(
                'test_harmless_mixed_comparison'))
        suite.addTest(test.datetimetester.TestTimeDelta('test_hash_equality'))
        suite.addTest(
            test.datetimetester.TestTimeDelta('test_massive_normalization'))
        suite.addTest(
            test.datetimetester.TestTimeDelta('test_microsecond_rounding'))
        suite.addTest(test.datetimetester.TestTimeDelta('test_overflow'))
        suite.addTest(test.datetimetester.TestTimeDelta('test_pickling'))
        suite.addTest(test.datetimetester.TestTimeDelta('test_remainder'))
        suite.addTest(test.datetimetester.TestTimeDelta('test_repr'))
        suite.addTest(
            test.datetimetester.TestTimeDelta('test_resolution_info'))
        suite.addTest(test.datetimetester.TestTimeDelta('test_roundtrip'))
        suite.addTest(test.datetimetester.TestTimeDelta('test_str'))
        suite.addTest(
            test.datetimetester.TestTimeDelta('test_subclass_timedelta'))
        suite.addTest(test.datetimetester.TestTimeDelta('test_total_seconds'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_1653736'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_argument_passing'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_aware_compare'))
        suite.addTest(
            test.datetimetester.TestTimeTZ('test_backdoor_resistance'))
        suite.addTest(
            test.datetimetester.TestTimeTZ('test_bad_constructor_arguments'))
        suite.addTest(
            test.datetimetester.TestTimeTZ('test_bad_tzinfo_classes'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_basic_attributes'))
        suite.addTest(
            test.datetimetester.TestTimeTZ('test_basic_attributes_nonzero'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_bool'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_comparing'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_empty'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_format'))
        suite.addTest(
            test.datetimetester.TestTimeTZ('test_harmful_mixed_comparison'))
        suite.addTest(
            test.datetimetester.TestTimeTZ('test_harmless_mixed_comparison'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_hash_edge_cases'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_hash_equality'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_isoformat'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestTimeTZ('test_mixed_compare')))
        suite.addTest(test.datetimetester.TestTimeTZ('test_more_bool'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_pickling'))
        suite.addTest(
            test.datetimetester.TestTimeTZ('test_pickling_subclass_time'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_replace'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_repr'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_resolution_info'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_roundtrip'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_str'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_strftime'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_subclass_time'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_subclass_timetz'))
        suite.addTest(test.datetimetester.TestTimeTZ('test_tzinfo_classes'))
        suite.addTest(
            test.datetimetester.TestTimeTZ('test_utc_offset_out_of_bounds'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestTimeTZ('test_zones')))
        suite.addTest(test.datetimetester.TestTimeZone('test_aware_datetime'))
        suite.addTest(test.datetimetester.TestTimeZone('test_class_members'))
        suite.addTest(test.datetimetester.TestTimeZone('test_comparison'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestTimeZone('test_constructor')))
        suite.addTest(test.datetimetester.TestTimeZone('test_copy'))
        suite.addTest(test.datetimetester.TestTimeZone('test_deepcopy'))
        suite.addTest(test.datetimetester.TestTimeZone('test_dst'))
        suite.addTest(test.datetimetester.TestTimeZone('test_fromutc'))
        suite.addTest(test.datetimetester.TestTimeZone('test_inheritance'))
        suite.addTest(test.datetimetester.TestTimeZone('test_pickle'))
        suite.addTest(test.datetimetester.TestTimeZone('test_repr'))
        suite.addTest(test.datetimetester.TestTimeZone('test_str'))
        suite.addTest(test.datetimetester.TestTimeZone('test_tzname'))
        suite.addTest(test.datetimetester.TestTimeZone('test_utcoffset'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestTimezoneConversions('test_bogus_dst'))
        )  # SystemError: Object reference not set to an instance of an object.
        suite.addTest(test.datetimetester.TestTimezoneConversions('test_easy'))
        suite.addTest(
            unittest.expectedFailure(
                test.datetimetester.TestTimezoneConversions('test_fromutc')))
        suite.addTest(
            test.datetimetester.TestTimezoneConversions('test_tricky'))
        return suite

    else:
        return loader.loadTestsFromModule(test.datetimetester, pattern)
Exemplo n.º 51
0
            self.assertEqual(current_spectra[i].size, expected_spectra[i].size)
            np.testing.assert_almost_equal(current_spectra[i],
                                           expected_spectra[i],
                                           decimal=1)

    return test_with_file


KNOWN_FAIL = (
    'test_cube_no_resu',
    'test_ecran_cube_no_resu',
    'test_ecran_no_resu',
    'test_effet_sol_no_resu',
    'test_face_no_resu',
    'test_impedance_sol_no_resu',
    'test_rayonnement_batiment_no_resu',
    'test_source_ponctuelle_no_resu',
)

# Retrieve all the available "TEST_XX" xml files and make a test for each one
for test_file in os.listdir(TEST_PROBLEM_DIR):
    if test_file.startswith('TEST_') and test_file.endswith('xml'):
        methodname = test_file.split('.')[0].lower()
        method = make_test_with_file(test_file)
        if methodname in KNOWN_FAIL:
            method = unittest.expectedFailure(method)
        setattr(TestTympan, methodname, method)

if __name__ == '__main__':
    unittest.main()
Exemplo n.º 52
0
def expectedFailurePY2(func):
    if not PY2:
        return func
    return unittest.expectedFailure(func)
Exemplo n.º 53
0
                                  turbulent=False)

        width = 10
        height = 10

        for i in range(0, height):
            for j in range(0, width):
                f = 0.5 + t.turbulence(imath.V2f(i / 50.0, j / 50.0))
                self.assertAlmostEqual(f, expected[i * height + j], 5)

    def testNaN(self):

        t = IECore.TurbulenceV2ff(octaves=28,
                                  gain=0.35,
                                  lacunarity=2,
                                  turbulent=True)

        f = t.turbulence(imath.V2f(21.3, 51.2))
        self.assertTrue(f == f)


if sys.platform == "darwin":

    # These fail because MacOS uses libc++, and libc++ has a
    # different `std::random_shuffle()` than libstdc++.

    TestTurbulence.test2d = unittest.expectedFailure(TestTurbulence.test2d)

if __name__ == "__main__":
    unittest.main()
Exemplo n.º 54
0
Arquivo: base.py Projeto: Nick-1/shop
def expected_failure_if_grappelli(func):
    if 'grappelli' in settings.INSTALLED_APPS:
        return unittest.expectedFailure(func)
    return func
Exemplo n.º 55
0
def expected_failure_if_suit(func):
    if 'suit' in settings.INSTALLED_APPS:
        return unittest.expectedFailure(func)
    return func
Exemplo n.º 56
0
def expect_failure_if_no_gpu(test):
    if not torch.cuda.is_available():
        return unittest.expectedFailure(test)
    else:
        return test
Exemplo n.º 57
0
  def testQuantityUnitOnMovement(self):
    """Make sure that changing default quantity unit on resource does not
       affect to movement.
       In this test, always use Base.edit method. Because Base.edit is
       used when real user edit document through edit form.
    """
    # Set up quantity unit categories
    # weight
    quantity_unit_category_value = self.portal.portal_categories.quantity_unit
    quantity_unit_weight = quantity_unit_category_value._getOb('weight', None)
    if quantity_unit_weight is None:
      quantity_unit_weight = quantity_unit_category_value.newContent(
        id='weight', portal_type='Category')
    quantity_unit_gram = quantity_unit_weight._getOb('gram', None)
    if quantity_unit_gram is None:
      quantity_unit_gram = quantity_unit_weight.newContent(
        portal_type='Category', id='gram')
    # volume
    quantity_unit_volume = quantity_unit_category_value._getOb('volume', None)
    if quantity_unit_volume is None:
      quantity_unit_volume = quantity_unit_category_value.newContent(
        id='volume', portal_type='Category')
    quantity_unit_liter = quantity_unit_volume._getOb('liter', None)
    if quantity_unit_liter is None:
      quantity_unit_liter = quantity_unit_volume.newContent(
        portal_type='Category', id='liter')
    self.commit()

    # Create resource
    resource_value = self.portal.getDefaultModule(
      self.product_portal_type).newContent(portal_type=self.product_portal_type)
    resource_value.edit(quantity_unit_value_list=[
        quantity_unit_gram, quantity_unit_liter])
    self.commit()
    self.assertEqual(resource_value.getDefaultQuantityUnitValue(),
                     quantity_unit_gram)

    # Create sale order line
    sale_order = self.portal.getDefaultModule('Sale Order').newContent(
      portal_type='Sale Order')
    sale_order_line = sale_order.newContent(
      portal_type=self.sale_order_line_portal_type)
    self.commit()

    # Set resource to movement
    sale_order_line.edit(resource_value=resource_value)
    self.commit()
    self.assertEqual(sale_order_line.getQuantityUnitValue(),
                     quantity_unit_gram)

    # Select different quantity unit
    sale_order_line.edit(quantity_unit_value=quantity_unit_liter)
    self.commit()
    self.assertEqual(sale_order_line.getQuantityUnitValue(),
                     quantity_unit_liter)

    # Select empty(no quantity unit)
    sale_order_line.edit(quantity_unit_value=None)
    self.commit()

    # Select default quantity unit again
    sale_order_line.edit(quantity_unit_value=quantity_unit_gram)
    self.commit()
    self.assertEqual(sale_order_line.getQuantityUnitValue(),
                     quantity_unit_gram)

    # Change default quantity unit on resource
    # Now liter is default quantity unit.
    resource_value.edit(quantity_unit_value_list=[
        quantity_unit_liter, quantity_unit_gram])
    self.commit()

    # Check existing movement again and make sure that quantity
    # unit is not changed.
    expectedFailure(self.assertEqual)(
      sale_order_line.getQuantityUnitValue(),
      quantity_unit_gram)
Exemplo n.º 58
0
class PathLikeTests(NtpathTestCase):

    path = ntpath

    def setUp(self):
        self.file_name = os_helper.TESTFN
        self.file_path = FakePath(os_helper.TESTFN)
        self.addCleanup(os_helper.unlink, self.file_name)
        with open(self.file_name, 'xb', 0) as file:
            file.write(b"test_ntpath.PathLikeTests")

    def _check_function(self, func):
        self.assertPathEqual(func(self.file_path), func(self.file_name))

    def test_path_normcase(self):
        self._check_function(self.path.normcase)
        if sys.platform == 'win32':
            self.assertEqual(ntpath.normcase('\u03a9\u2126'), 'ωΩ')

    # TODO: RUSTPYTHON, AssertionError: 'ωω' != 'ωΩ'
    if sys.platform == "win32":
        test_path_normcase = unittest.expectedFailure(test_path_normcase)

    def test_path_isabs(self):
        self._check_function(self.path.isabs)

    def test_path_join(self):
        self.assertEqual(self.path.join('a', FakePath('b'), 'c'),
                         self.path.join('a', 'b', 'c'))

    def test_path_split(self):
        self._check_function(self.path.split)

    def test_path_splitext(self):
        self._check_function(self.path.splitext)

    def test_path_splitdrive(self):
        self._check_function(self.path.splitdrive)

    def test_path_basename(self):
        self._check_function(self.path.basename)

    def test_path_dirname(self):
        self._check_function(self.path.dirname)

    def test_path_islink(self):
        self._check_function(self.path.islink)

    def test_path_lexists(self):
        self._check_function(self.path.lexists)

    def test_path_ismount(self):
        self._check_function(self.path.ismount)

    def test_path_expanduser(self):
        self._check_function(self.path.expanduser)

    def test_path_expandvars(self):
        self._check_function(self.path.expandvars)

    def test_path_normpath(self):
        self._check_function(self.path.normpath)

    def test_path_abspath(self):
        self._check_function(self.path.abspath)

    def test_path_realpath(self):
        self._check_function(self.path.realpath)

    def test_path_relpath(self):
        self._check_function(self.path.relpath)

    def test_path_commonpath(self):
        common_path = self.path.commonpath([self.file_path, self.file_name])
        self.assertPathEqual(common_path, self.file_name)

    def test_path_isdir(self):
        self._check_function(self.path.isdir)
Exemplo n.º 59
0
 def setUpClass(cls):
     # Because edge out-c has a native width, we expect it to fail
     #  the base test_mark_edge. The test_mark_edge_pass case has been
     #  developed to test correct functionality
     cls.test_mark_edge = unittest.expectedFailure(cls.test_mark_edge)
Exemplo n.º 60
0
class TestNtpath(NtpathTestCase):
    def test_splitext(self):
        tester('ntpath.splitext("foo.ext")', ('foo', '.ext'))
        tester('ntpath.splitext("/foo/foo.ext")', ('/foo/foo', '.ext'))
        tester('ntpath.splitext(".ext")', ('.ext', ''))
        tester('ntpath.splitext("\\foo.ext\\foo")', ('\\foo.ext\\foo', ''))
        tester('ntpath.splitext("foo.ext\\")', ('foo.ext\\', ''))
        tester('ntpath.splitext("")', ('', ''))
        tester('ntpath.splitext("foo.bar.ext")', ('foo.bar', '.ext'))
        tester('ntpath.splitext("xx/foo.bar.ext")', ('xx/foo.bar', '.ext'))
        tester('ntpath.splitext("xx\\foo.bar.ext")', ('xx\\foo.bar', '.ext'))
        tester('ntpath.splitext("c:a/b\\c.d")', ('c:a/b\\c', '.d'))

    def test_splitdrive(self):
        tester('ntpath.splitdrive("c:\\foo\\bar")',
               ('c:', '\\foo\\bar'))
        tester('ntpath.splitdrive("c:/foo/bar")',
               ('c:', '/foo/bar'))
        tester('ntpath.splitdrive("\\\\conky\\mountpoint\\foo\\bar")',
               ('\\\\conky\\mountpoint', '\\foo\\bar'))
        tester('ntpath.splitdrive("//conky/mountpoint/foo/bar")',
               ('//conky/mountpoint', '/foo/bar'))
        tester('ntpath.splitdrive("\\\\\\conky\\mountpoint\\foo\\bar")',
            ('', '\\\\\\conky\\mountpoint\\foo\\bar'))
        tester('ntpath.splitdrive("///conky/mountpoint/foo/bar")',
            ('', '///conky/mountpoint/foo/bar'))
        tester('ntpath.splitdrive("\\\\conky\\\\mountpoint\\foo\\bar")',
               ('', '\\\\conky\\\\mountpoint\\foo\\bar'))
        tester('ntpath.splitdrive("//conky//mountpoint/foo/bar")',
               ('', '//conky//mountpoint/foo/bar'))
        # Issue #19911: UNC part containing U+0130
        self.assertEqual(ntpath.splitdrive('//conky/MOUNTPOİNT/foo/bar'),
                         ('//conky/MOUNTPOİNT', '/foo/bar'))

    def test_split(self):
        tester('ntpath.split("c:\\foo\\bar")', ('c:\\foo', 'bar'))
        tester('ntpath.split("\\\\conky\\mountpoint\\foo\\bar")',
               ('\\\\conky\\mountpoint\\foo', 'bar'))

        tester('ntpath.split("c:\\")', ('c:\\', ''))
        tester('ntpath.split("\\\\conky\\mountpoint\\")',
               ('\\\\conky\\mountpoint\\', ''))

        tester('ntpath.split("c:/")', ('c:/', ''))
        tester('ntpath.split("//conky/mountpoint/")', ('//conky/mountpoint/', ''))

    def test_isabs(self):
        tester('ntpath.isabs("c:\\")', 1)
        tester('ntpath.isabs("\\\\conky\\mountpoint\\")', 1)
        tester('ntpath.isabs("\\foo")', 1)
        tester('ntpath.isabs("\\foo\\bar")', 1)

    def test_commonprefix(self):
        tester('ntpath.commonprefix(["/home/swenson/spam", "/home/swen/spam"])',
               "/home/swen")
        tester('ntpath.commonprefix(["\\home\\swen\\spam", "\\home\\swen\\eggs"])',
               "\\home\\swen\\")
        tester('ntpath.commonprefix(["/home/swen/spam", "/home/swen/spam"])',
               "/home/swen/spam")

    def test_join(self):
        tester('ntpath.join("")', '')
        tester('ntpath.join("", "", "")', '')
        tester('ntpath.join("a")', 'a')
        tester('ntpath.join("/a")', '/a')
        tester('ntpath.join("\\a")', '\\a')
        tester('ntpath.join("a:")', 'a:')
        tester('ntpath.join("a:", "\\b")', 'a:\\b')
        tester('ntpath.join("a", "\\b")', '\\b')
        tester('ntpath.join("a", "b", "c")', 'a\\b\\c')
        tester('ntpath.join("a\\", "b", "c")', 'a\\b\\c')
        tester('ntpath.join("a", "b\\", "c")', 'a\\b\\c')
        tester('ntpath.join("a", "b", "\\c")', '\\c')
        tester('ntpath.join("d:\\", "\\pleep")', 'd:\\pleep')
        tester('ntpath.join("d:\\", "a", "b")', 'd:\\a\\b')

        tester("ntpath.join('', 'a')", 'a')
        tester("ntpath.join('', '', '', '', 'a')", 'a')
        tester("ntpath.join('a', '')", 'a\\')
        tester("ntpath.join('a', '', '', '', '')", 'a\\')
        tester("ntpath.join('a\\', '')", 'a\\')
        tester("ntpath.join('a\\', '', '', '', '')", 'a\\')
        tester("ntpath.join('a/', '')", 'a/')

        tester("ntpath.join('a/b', 'x/y')", 'a/b\\x/y')
        tester("ntpath.join('/a/b', 'x/y')", '/a/b\\x/y')
        tester("ntpath.join('/a/b/', 'x/y')", '/a/b/x/y')
        tester("ntpath.join('c:', 'x/y')", 'c:x/y')
        tester("ntpath.join('c:a/b', 'x/y')", 'c:a/b\\x/y')
        tester("ntpath.join('c:a/b/', 'x/y')", 'c:a/b/x/y')
        tester("ntpath.join('c:/', 'x/y')", 'c:/x/y')
        tester("ntpath.join('c:/a/b', 'x/y')", 'c:/a/b\\x/y')
        tester("ntpath.join('c:/a/b/', 'x/y')", 'c:/a/b/x/y')
        tester("ntpath.join('//computer/share', 'x/y')", '//computer/share\\x/y')
        tester("ntpath.join('//computer/share/', 'x/y')", '//computer/share/x/y')
        tester("ntpath.join('//computer/share/a/b', 'x/y')", '//computer/share/a/b\\x/y')

        tester("ntpath.join('a/b', '/x/y')", '/x/y')
        tester("ntpath.join('/a/b', '/x/y')", '/x/y')
        tester("ntpath.join('c:', '/x/y')", 'c:/x/y')
        tester("ntpath.join('c:a/b', '/x/y')", 'c:/x/y')
        tester("ntpath.join('c:/', '/x/y')", 'c:/x/y')
        tester("ntpath.join('c:/a/b', '/x/y')", 'c:/x/y')
        tester("ntpath.join('//computer/share', '/x/y')", '//computer/share/x/y')
        tester("ntpath.join('//computer/share/', '/x/y')", '//computer/share/x/y')
        tester("ntpath.join('//computer/share/a', '/x/y')", '//computer/share/x/y')

        tester("ntpath.join('c:', 'C:x/y')", 'C:x/y')
        tester("ntpath.join('c:a/b', 'C:x/y')", 'C:a/b\\x/y')
        tester("ntpath.join('c:/', 'C:x/y')", 'C:/x/y')
        tester("ntpath.join('c:/a/b', 'C:x/y')", 'C:/a/b\\x/y')

        for x in ('', 'a/b', '/a/b', 'c:', 'c:a/b', 'c:/', 'c:/a/b',
                  '//computer/share', '//computer/share/', '//computer/share/a/b'):
            for y in ('d:', 'd:x/y', 'd:/', 'd:/x/y',
                      '//machine/common', '//machine/common/', '//machine/common/x/y'):
                tester("ntpath.join(%r, %r)" % (x, y), y)

        tester("ntpath.join('\\\\computer\\share\\', 'a', 'b')", '\\\\computer\\share\\a\\b')
        tester("ntpath.join('\\\\computer\\share', 'a', 'b')", '\\\\computer\\share\\a\\b')
        tester("ntpath.join('\\\\computer\\share', 'a\\b')", '\\\\computer\\share\\a\\b')
        tester("ntpath.join('//computer/share/', 'a', 'b')", '//computer/share/a\\b')
        tester("ntpath.join('//computer/share', 'a', 'b')", '//computer/share\\a\\b')
        tester("ntpath.join('//computer/share', 'a/b')", '//computer/share\\a/b')

    def test_normpath(self):
        tester("ntpath.normpath('A//////././//.//B')", r'A\B')
        tester("ntpath.normpath('A/./B')", r'A\B')
        tester("ntpath.normpath('A/foo/../B')", r'A\B')
        tester("ntpath.normpath('C:A//B')", r'C:A\B')
        tester("ntpath.normpath('D:A/./B')", r'D:A\B')
        tester("ntpath.normpath('e:A/foo/../B')", r'e:A\B')

        tester("ntpath.normpath('C:///A//B')", r'C:\A\B')
        tester("ntpath.normpath('D:///A/./B')", r'D:\A\B')
        tester("ntpath.normpath('e:///A/foo/../B')", r'e:\A\B')

        tester("ntpath.normpath('..')", r'..')
        tester("ntpath.normpath('.')", r'.')
        tester("ntpath.normpath('')", r'.')
        tester("ntpath.normpath('/')", '\\')
        tester("ntpath.normpath('c:/')", 'c:\\')
        tester("ntpath.normpath('/../.././..')", '\\')
        tester("ntpath.normpath('c:/../../..')", 'c:\\')
        tester("ntpath.normpath('../.././..')", r'..\..\..')
        tester("ntpath.normpath('K:../.././..')", r'K:..\..\..')
        tester("ntpath.normpath('C:////a/b')", r'C:\a\b')
        tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b')

        tester("ntpath.normpath('\\\\.\\NUL')", r'\\.\NUL')
        tester("ntpath.normpath('\\\\?\\D:/XY\\Z')", r'\\?\D:/XY\Z')

    def test_realpath_curdir(self):
        expected = ntpath.normpath(os.getcwd())
        tester("ntpath.realpath('.')", expected)
        tester("ntpath.realpath('./.')", expected)
        tester("ntpath.realpath('/'.join(['.'] * 100))", expected)
        tester("ntpath.realpath('.\\.')", expected)
        tester("ntpath.realpath('\\'.join(['.'] * 100))", expected)

    def test_realpath_pardir(self):
        expected = ntpath.normpath(os.getcwd())
        tester("ntpath.realpath('..')", ntpath.dirname(expected))
        tester("ntpath.realpath('../..')",
               ntpath.dirname(ntpath.dirname(expected)))
        tester("ntpath.realpath('/'.join(['..'] * 50))",
               ntpath.splitdrive(expected)[0] + '\\')
        tester("ntpath.realpath('..\\..')",
               ntpath.dirname(ntpath.dirname(expected)))
        tester("ntpath.realpath('\\'.join(['..'] * 50))",
               ntpath.splitdrive(expected)[0] + '\\')

    @os_helper.skip_unless_symlink
    @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
    def test_realpath_basic(self):
        ABSTFN = ntpath.abspath(os_helper.TESTFN)
        open(ABSTFN, "wb").close()
        self.addCleanup(os_helper.unlink, ABSTFN)
        self.addCleanup(os_helper.unlink, ABSTFN + "1")

        os.symlink(ABSTFN, ABSTFN + "1")
        self.assertPathEqual(ntpath.realpath(ABSTFN + "1"), ABSTFN)
        self.assertPathEqual(ntpath.realpath(os.fsencode(ABSTFN + "1")),
                         os.fsencode(ABSTFN))

    @os_helper.skip_unless_symlink
    @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
    def test_realpath_strict(self):
        # Bug #43757: raise FileNotFoundError in strict mode if we encounter
        # a path that does not exist.
        ABSTFN = ntpath.abspath(os_helper.TESTFN)
        os.symlink(ABSTFN + "1", ABSTFN)
        self.addCleanup(os_helper.unlink, ABSTFN)
        self.assertRaises(FileNotFoundError, ntpath.realpath, ABSTFN, strict=True)
        self.assertRaises(FileNotFoundError, ntpath.realpath, ABSTFN + "2", strict=True)

    # TODO: RUSTPYTHON, TypeError: got an unexpected keyword argument 'strict'
    if sys.platform == "win32":
        test_realpath_strict = unittest.expectedFailure(test_realpath_strict)

    @os_helper.skip_unless_symlink
    @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
    def test_realpath_relative(self):
        ABSTFN = ntpath.abspath(os_helper.TESTFN)
        open(ABSTFN, "wb").close()
        self.addCleanup(os_helper.unlink, ABSTFN)
        self.addCleanup(os_helper.unlink, ABSTFN + "1")

        os.symlink(ABSTFN, ntpath.relpath(ABSTFN + "1"))
        self.assertPathEqual(ntpath.realpath(ABSTFN + "1"), ABSTFN)

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    @os_helper.skip_unless_symlink
    @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
    def test_realpath_broken_symlinks(self):
        ABSTFN = ntpath.abspath(os_helper.TESTFN)
        os.mkdir(ABSTFN)
        self.addCleanup(os_helper.rmtree, ABSTFN)

        with os_helper.change_cwd(ABSTFN):
            os.mkdir("subdir")
            os.chdir("subdir")
            os.symlink(".", "recursive")
            os.symlink("..", "parent")
            os.chdir("..")
            os.symlink(".", "self")
            os.symlink("missing", "broken")
            os.symlink(r"broken\bar", "broken1")
            os.symlink(r"self\self\broken", "broken2")
            os.symlink(r"subdir\parent\subdir\parent\broken", "broken3")
            os.symlink(ABSTFN + r"\broken", "broken4")
            os.symlink(r"recursive\..\broken", "broken5")

            self.assertPathEqual(ntpath.realpath("broken"),
                                 ABSTFN + r"\missing")
            self.assertPathEqual(ntpath.realpath(r"broken\foo"),
                                 ABSTFN + r"\missing\foo")
            # bpo-38453: We no longer recursively resolve segments of relative
            # symlinks that the OS cannot resolve.
            self.assertPathEqual(ntpath.realpath(r"broken1"),
                                 ABSTFN + r"\broken\bar")
            self.assertPathEqual(ntpath.realpath(r"broken1\baz"),
                                 ABSTFN + r"\broken\bar\baz")
            self.assertPathEqual(ntpath.realpath("broken2"),
                                 ABSTFN + r"\self\self\missing")
            self.assertPathEqual(ntpath.realpath("broken3"),
                                 ABSTFN + r"\subdir\parent\subdir\parent\missing")
            self.assertPathEqual(ntpath.realpath("broken4"),
                                 ABSTFN + r"\missing")
            self.assertPathEqual(ntpath.realpath("broken5"),
                                 ABSTFN + r"\missing")

            self.assertPathEqual(ntpath.realpath(b"broken"),
                                 os.fsencode(ABSTFN + r"\missing"))
            self.assertPathEqual(ntpath.realpath(rb"broken\foo"),
                                 os.fsencode(ABSTFN + r"\missing\foo"))
            self.assertPathEqual(ntpath.realpath(rb"broken1"),
                                 os.fsencode(ABSTFN + r"\broken\bar"))
            self.assertPathEqual(ntpath.realpath(rb"broken1\baz"),
                                 os.fsencode(ABSTFN + r"\broken\bar\baz"))
            self.assertPathEqual(ntpath.realpath(b"broken2"),
                                 os.fsencode(ABSTFN + r"\self\self\missing"))
            self.assertPathEqual(ntpath.realpath(rb"broken3"),
                                 os.fsencode(ABSTFN + r"\subdir\parent\subdir\parent\missing"))
            self.assertPathEqual(ntpath.realpath(b"broken4"),
                                 os.fsencode(ABSTFN + r"\missing"))
            self.assertPathEqual(ntpath.realpath(b"broken5"),
                                 os.fsencode(ABSTFN + r"\missing"))

    @unittest.skip("TODO: RUSTPYTHON, leaves behind TESTFN")
    @os_helper.skip_unless_symlink
    @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
    def test_realpath_symlink_loops(self):
        # Symlink loops in non-strict mode are non-deterministic as to which
        # path is returned, but it will always be the fully resolved path of
        # one member of the cycle
        ABSTFN = ntpath.abspath(os_helper.TESTFN)
        self.addCleanup(os_helper.unlink, ABSTFN)
        self.addCleanup(os_helper.unlink, ABSTFN + "1")
        self.addCleanup(os_helper.unlink, ABSTFN + "2")
        self.addCleanup(os_helper.unlink, ABSTFN + "y")
        self.addCleanup(os_helper.unlink, ABSTFN + "c")
        self.addCleanup(os_helper.unlink, ABSTFN + "a")

        os.symlink(ABSTFN, ABSTFN)
        self.assertPathEqual(ntpath.realpath(ABSTFN), ABSTFN)

        os.symlink(ABSTFN + "1", ABSTFN + "2")
        os.symlink(ABSTFN + "2", ABSTFN + "1")
        expected = (ABSTFN + "1", ABSTFN + "2")
        self.assertPathIn(ntpath.realpath(ABSTFN + "1"), expected)
        self.assertPathIn(ntpath.realpath(ABSTFN + "2"), expected)

        self.assertPathIn(ntpath.realpath(ABSTFN + "1\\x"),
                          (ntpath.join(r, "x") for r in expected))
        self.assertPathEqual(ntpath.realpath(ABSTFN + "1\\.."),
                             ntpath.dirname(ABSTFN))
        self.assertPathEqual(ntpath.realpath(ABSTFN + "1\\..\\x"),
                             ntpath.dirname(ABSTFN) + "\\x")
        os.symlink(ABSTFN + "x", ABSTFN + "y")
        self.assertPathEqual(ntpath.realpath(ABSTFN + "1\\..\\"
                                             + ntpath.basename(ABSTFN) + "y"),
                             ABSTFN + "x")
        self.assertPathIn(ntpath.realpath(ABSTFN + "1\\..\\"
                                          + ntpath.basename(ABSTFN) + "1"),
                          expected)

        os.symlink(ntpath.basename(ABSTFN) + "a\\b", ABSTFN + "a")
        self.assertPathEqual(ntpath.realpath(ABSTFN + "a"), ABSTFN + "a")

        os.symlink("..\\" + ntpath.basename(ntpath.dirname(ABSTFN))
                   + "\\" + ntpath.basename(ABSTFN) + "c", ABSTFN + "c")
        self.assertPathEqual(ntpath.realpath(ABSTFN + "c"), ABSTFN + "c")

        # Test using relative path as well.
        self.assertPathEqual(ntpath.realpath(ntpath.basename(ABSTFN)), ABSTFN)

    @os_helper.skip_unless_symlink
    @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
    def test_realpath_symlink_loops_strict(self):
        # Symlink loops raise OSError in strict mode
        ABSTFN = ntpath.abspath(os_helper.TESTFN)
        self.addCleanup(os_helper.unlink, ABSTFN)
        self.addCleanup(os_helper.unlink, ABSTFN + "1")
        self.addCleanup(os_helper.unlink, ABSTFN + "2")
        self.addCleanup(os_helper.unlink, ABSTFN + "y")
        self.addCleanup(os_helper.unlink, ABSTFN + "c")
        self.addCleanup(os_helper.unlink, ABSTFN + "a")

        os.symlink(ABSTFN, ABSTFN)
        self.assertRaises(OSError, ntpath.realpath, ABSTFN, strict=True)

        os.symlink(ABSTFN + "1", ABSTFN + "2")
        os.symlink(ABSTFN + "2", ABSTFN + "1")
        self.assertRaises(OSError, ntpath.realpath, ABSTFN + "1", strict=True)
        self.assertRaises(OSError, ntpath.realpath, ABSTFN + "2", strict=True)
        self.assertRaises(OSError, ntpath.realpath, ABSTFN + "1\\x", strict=True)
        # Windows eliminates '..' components before resolving links, so the
        # following call is not expected to raise.
        self.assertPathEqual(ntpath.realpath(ABSTFN + "1\\..", strict=True),
                             ntpath.dirname(ABSTFN))
        self.assertRaises(OSError, ntpath.realpath, ABSTFN + "1\\..\\x", strict=True)
        os.symlink(ABSTFN + "x", ABSTFN + "y")
        self.assertRaises(OSError, ntpath.realpath, ABSTFN + "1\\..\\"
                                             + ntpath.basename(ABSTFN) + "y",
                                             strict=True)
        self.assertRaises(OSError, ntpath.realpath,
                          ABSTFN + "1\\..\\" + ntpath.basename(ABSTFN) + "1",
                          strict=True)

        os.symlink(ntpath.basename(ABSTFN) + "a\\b", ABSTFN + "a")
        self.assertRaises(OSError, ntpath.realpath, ABSTFN + "a", strict=True)

        os.symlink("..\\" + ntpath.basename(ntpath.dirname(ABSTFN))
                   + "\\" + ntpath.basename(ABSTFN) + "c", ABSTFN + "c")
        self.assertRaises(OSError, ntpath.realpath, ABSTFN + "c", strict=True)

        # Test using relative path as well.
        self.assertRaises(OSError, ntpath.realpath, ntpath.basename(ABSTFN),
                          strict=True)

    # TODO: RUSTPYTHON, FileExistsError: [Errno 183] Cannot create a file when that file already exists. (os error 183): 'None' -> 'None'
    if sys.platform == "win32":
        test_realpath_symlink_loops_strict = unittest.expectedFailure(test_realpath_symlink_loops_strict)

    @os_helper.skip_unless_symlink
    @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
    def test_realpath_symlink_prefix(self):
        ABSTFN = ntpath.abspath(os_helper.TESTFN)
        self.addCleanup(os_helper.unlink, ABSTFN + "3")
        self.addCleanup(os_helper.unlink, "\\\\?\\" + ABSTFN + "3.")
        self.addCleanup(os_helper.unlink, ABSTFN + "3link")
        self.addCleanup(os_helper.unlink, ABSTFN + "3.link")

        with open(ABSTFN + "3", "wb") as f:
            f.write(b'0')
        os.symlink(ABSTFN + "3", ABSTFN + "3link")

        with open("\\\\?\\" + ABSTFN + "3.", "wb") as f:
            f.write(b'1')
        os.symlink("\\\\?\\" + ABSTFN + "3.", ABSTFN + "3.link")

        self.assertPathEqual(ntpath.realpath(ABSTFN + "3link"),
                             ABSTFN + "3")
        self.assertPathEqual(ntpath.realpath(ABSTFN + "3.link"),
                             "\\\\?\\" + ABSTFN + "3.")

        # Resolved paths should be usable to open target files
        with open(ntpath.realpath(ABSTFN + "3link"), "rb") as f:
            self.assertEqual(f.read(), b'0')
        with open(ntpath.realpath(ABSTFN + "3.link"), "rb") as f:
            self.assertEqual(f.read(), b'1')

        # When the prefix is included, it is not stripped
        self.assertPathEqual(ntpath.realpath("\\\\?\\" + ABSTFN + "3link"),
                             "\\\\?\\" + ABSTFN + "3")
        self.assertPathEqual(ntpath.realpath("\\\\?\\" + ABSTFN + "3.link"),
                             "\\\\?\\" + ABSTFN + "3.")

    @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
    def test_realpath_nul(self):
        tester("ntpath.realpath('NUL')", r'\\.\NUL')

    @unittest.skipUnless(HAVE_GETFINALPATHNAME, 'need _getfinalpathname')
    @unittest.skipUnless(HAVE_GETSHORTPATHNAME, 'need _getshortpathname')
    def test_realpath_cwd(self):
        ABSTFN = ntpath.abspath(os_helper.TESTFN)

        os_helper.unlink(ABSTFN)
        os_helper.rmtree(ABSTFN)
        os.mkdir(ABSTFN)
        self.addCleanup(os_helper.rmtree, ABSTFN)

        test_dir_long = ntpath.join(ABSTFN, "MyVeryLongDirectoryName")
        os.mkdir(test_dir_long)

        test_dir_short = _getshortpathname(test_dir_long)
        test_file_long = ntpath.join(test_dir_long, "file.txt")
        test_file_short = ntpath.join(test_dir_short, "file.txt")

        with open(test_file_long, "wb") as f:
            f.write(b"content")

        self.assertPathEqual(test_file_long, ntpath.realpath(test_file_short))

        with os_helper.change_cwd(test_dir_long):
            self.assertPathEqual(test_file_long, ntpath.realpath("file.txt"))
        with os_helper.change_cwd(test_dir_long.lower()):
            self.assertPathEqual(test_file_long, ntpath.realpath("file.txt"))
        with os_helper.change_cwd(test_dir_short):
            self.assertPathEqual(test_file_long, ntpath.realpath("file.txt"))

    @unittest.skipIf(sys.platform == "win32", "TODO: RUSTPYTHON, ValueError: illegal environment variable name")
    def test_expandvars(self):
        with os_helper.EnvironmentVarGuard() as env:
            env.clear()
            env["foo"] = "bar"
            env["{foo"] = "baz1"
            env["{foo}"] = "baz2"
            tester('ntpath.expandvars("foo")', "foo")
            tester('ntpath.expandvars("$foo bar")', "bar bar")
            tester('ntpath.expandvars("${foo}bar")', "barbar")
            tester('ntpath.expandvars("$[foo]bar")', "$[foo]bar")
            tester('ntpath.expandvars("$bar bar")', "$bar bar")
            tester('ntpath.expandvars("$?bar")', "$?bar")
            tester('ntpath.expandvars("$foo}bar")', "bar}bar")
            tester('ntpath.expandvars("${foo")', "${foo")
            tester('ntpath.expandvars("${{foo}}")', "baz1}")
            tester('ntpath.expandvars("$foo$foo")', "barbar")
            tester('ntpath.expandvars("$bar$bar")', "$bar$bar")
            tester('ntpath.expandvars("%foo% bar")', "bar bar")
            tester('ntpath.expandvars("%foo%bar")', "barbar")
            tester('ntpath.expandvars("%foo%%foo%")', "barbar")
            tester('ntpath.expandvars("%%foo%%foo%foo%")', "%foo%foobar")
            tester('ntpath.expandvars("%?bar%")', "%?bar%")
            tester('ntpath.expandvars("%foo%%bar")', "bar%bar")
            tester('ntpath.expandvars("\'%foo%\'%bar")', "\'%foo%\'%bar")
            tester('ntpath.expandvars("bar\'%foo%")', "bar\'%foo%")

    @unittest.skipIf(sys.platform == "win32", "TODO: RUSTPYTHON, ValueError: illegal environment variable name")
    @unittest.skipUnless(os_helper.FS_NONASCII, 'need os_helper.FS_NONASCII')
    def test_expandvars_nonascii(self):
        def check(value, expected):
            tester('ntpath.expandvars(%r)' % value, expected)
        with os_helper.EnvironmentVarGuard() as env:
            env.clear()
            nonascii = os_helper.FS_NONASCII
            env['spam'] = nonascii
            env[nonascii] = 'ham' + nonascii
            check('$spam bar', '%s bar' % nonascii)
            check('$%s bar' % nonascii, '$%s bar' % nonascii)
            check('${spam}bar', '%sbar' % nonascii)
            check('${%s}bar' % nonascii, 'ham%sbar' % nonascii)
            check('$spam}bar', '%s}bar' % nonascii)
            check('$%s}bar' % nonascii, '$%s}bar' % nonascii)
            check('%spam% bar', '%s bar' % nonascii)
            check('%{}% bar'.format(nonascii), 'ham%s bar' % nonascii)
            check('%spam%bar', '%sbar' % nonascii)
            check('%{}%bar'.format(nonascii), 'ham%sbar' % nonascii)

    # TODO: RUSTPYTHON
    @unittest.expectedFailure
    def test_expanduser(self):
        tester('ntpath.expanduser("test")', 'test')

        with os_helper.EnvironmentVarGuard() as env:
            env.clear()
            tester('ntpath.expanduser("~test")', '~test')

            env['HOMEDRIVE'] = 'C:\\'
            env['HOMEPATH'] = 'Users\\eric'
            env['USERNAME'] = '******'
            tester('ntpath.expanduser("~test")', 'C:\\Users\\test')
            tester('ntpath.expanduser("~")', 'C:\\Users\\eric')

            del env['HOMEDRIVE']
            tester('ntpath.expanduser("~test")', 'Users\\test')
            tester('ntpath.expanduser("~")', 'Users\\eric')

            env.clear()
            env['USERPROFILE'] = 'C:\\Users\\eric'
            env['USERNAME'] = '******'
            tester('ntpath.expanduser("~test")', 'C:\\Users\\test')
            tester('ntpath.expanduser("~")', 'C:\\Users\\eric')
            tester('ntpath.expanduser("~test\\foo\\bar")',
                   'C:\\Users\\test\\foo\\bar')
            tester('ntpath.expanduser("~test/foo/bar")',
                   'C:\\Users\\test/foo/bar')
            tester('ntpath.expanduser("~\\foo\\bar")',
                   'C:\\Users\\eric\\foo\\bar')
            tester('ntpath.expanduser("~/foo/bar")',
                   'C:\\Users\\eric/foo/bar')

            # bpo-36264: ignore `HOME` when set on windows
            env.clear()
            env['HOME'] = 'F:\\'
            env['USERPROFILE'] = 'C:\\Users\\eric'
            env['USERNAME'] = '******'
            tester('ntpath.expanduser("~test")', 'C:\\Users\\test')
            tester('ntpath.expanduser("~")', 'C:\\Users\\eric')

            # bpo-39899: don't guess another user's home directory if
            # `%USERNAME% != basename(%USERPROFILE%)`
            env.clear()
            env['USERPROFILE'] = 'C:\\Users\\eric'
            env['USERNAME'] = '******'
            tester('ntpath.expanduser("~test")', '~test')
            tester('ntpath.expanduser("~")', 'C:\\Users\\eric')



    @unittest.skipUnless(nt, "abspath requires 'nt' module")
    def test_abspath(self):
        tester('ntpath.abspath("C:\\")', "C:\\")
        with os_helper.temp_cwd(os_helper.TESTFN) as cwd_dir: # bpo-31047
            tester('ntpath.abspath("")', cwd_dir)
            tester('ntpath.abspath(" ")', cwd_dir + "\\ ")
            tester('ntpath.abspath("?")', cwd_dir + "\\?")
            drive, _ = ntpath.splitdrive(cwd_dir)
            tester('ntpath.abspath("/abc/")', drive + "\\abc")

    def test_relpath(self):
        tester('ntpath.relpath("a")', 'a')
        tester('ntpath.relpath(ntpath.abspath("a"))', 'a')
        tester('ntpath.relpath("a/b")', 'a\\b')
        tester('ntpath.relpath("../a/b")', '..\\a\\b')
        with os_helper.temp_cwd(os_helper.TESTFN) as cwd_dir:
            currentdir = ntpath.basename(cwd_dir)
            tester('ntpath.relpath("a", "../b")', '..\\'+currentdir+'\\a')
            tester('ntpath.relpath("a/b", "../c")', '..\\'+currentdir+'\\a\\b')
        tester('ntpath.relpath("a", "b/c")', '..\\..\\a')
        tester('ntpath.relpath("c:/foo/bar/bat", "c:/x/y")', '..\\..\\foo\\bar\\bat')
        tester('ntpath.relpath("//conky/mountpoint/a", "//conky/mountpoint/b/c")', '..\\..\\a')
        tester('ntpath.relpath("a", "a")', '.')
        tester('ntpath.relpath("/foo/bar/bat", "/x/y/z")', '..\\..\\..\\foo\\bar\\bat')
        tester('ntpath.relpath("/foo/bar/bat", "/foo/bar")', 'bat')
        tester('ntpath.relpath("/foo/bar/bat", "/")', 'foo\\bar\\bat')
        tester('ntpath.relpath("/", "/foo/bar/bat")', '..\\..\\..')
        tester('ntpath.relpath("/foo/bar/bat", "/x")', '..\\foo\\bar\\bat')
        tester('ntpath.relpath("/x", "/foo/bar/bat")', '..\\..\\..\\x')
        tester('ntpath.relpath("/", "/")', '.')
        tester('ntpath.relpath("/a", "/a")', '.')
        tester('ntpath.relpath("/a/b", "/a/b")', '.')
        tester('ntpath.relpath("c:/foo", "C:/FOO")', '.')

    # TODO: RUSTPYTHON, FileExistsError: [Errno 183] Cannot create a file when that file already exists. (os error 183): 'None' -> 'None'
    if sys.platform == "win32":
        test_relpath = unittest.expectedFailure(test_relpath)

    def test_commonpath(self):
        def check(paths, expected):
            tester(('ntpath.commonpath(%r)' % paths).replace('\\\\', '\\'),
                   expected)
        def check_error(exc, paths):
            self.assertRaises(exc, ntpath.commonpath, paths)
            self.assertRaises(exc, ntpath.commonpath,
                              [os.fsencode(p) for p in paths])

        self.assertRaises(ValueError, ntpath.commonpath, [])
        check_error(ValueError, ['C:\\Program Files', 'Program Files'])
        check_error(ValueError, ['C:\\Program Files', 'C:Program Files'])
        check_error(ValueError, ['\\Program Files', 'Program Files'])
        check_error(ValueError, ['Program Files', 'C:\\Program Files'])
        check(['C:\\Program Files'], 'C:\\Program Files')
        check(['C:\\Program Files', 'C:\\Program Files'], 'C:\\Program Files')
        check(['C:\\Program Files\\', 'C:\\Program Files'],
              'C:\\Program Files')
        check(['C:\\Program Files\\', 'C:\\Program Files\\'],
              'C:\\Program Files')
        check(['C:\\\\Program Files', 'C:\\Program Files\\\\'],
              'C:\\Program Files')
        check(['C:\\.\\Program Files', 'C:\\Program Files\\.'],
              'C:\\Program Files')
        check(['C:\\', 'C:\\bin'], 'C:\\')
        check(['C:\\Program Files', 'C:\\bin'], 'C:\\')
        check(['C:\\Program Files', 'C:\\Program Files\\Bar'],
              'C:\\Program Files')
        check(['C:\\Program Files\\Foo', 'C:\\Program Files\\Bar'],
              'C:\\Program Files')
        check(['C:\\Program Files', 'C:\\Projects'], 'C:\\')
        check(['C:\\Program Files\\', 'C:\\Projects'], 'C:\\')

        check(['C:\\Program Files\\Foo', 'C:/Program Files/Bar'],
              'C:\\Program Files')
        check(['C:\\Program Files\\Foo', 'c:/program files/bar'],
              'C:\\Program Files')
        check(['c:/program files/bar', 'C:\\Program Files\\Foo'],
              'c:\\program files')

        check_error(ValueError, ['C:\\Program Files', 'D:\\Program Files'])

        check(['spam'], 'spam')
        check(['spam', 'spam'], 'spam')
        check(['spam', 'alot'], '')
        check(['and\\jam', 'and\\spam'], 'and')
        check(['and\\\\jam', 'and\\spam\\\\'], 'and')
        check(['and\\.\\jam', '.\\and\\spam'], 'and')
        check(['and\\jam', 'and\\spam', 'alot'], '')
        check(['and\\jam', 'and\\spam', 'and'], 'and')
        check(['C:and\\jam', 'C:and\\spam'], 'C:and')

        check([''], '')
        check(['', 'spam\\alot'], '')
        check_error(ValueError, ['', '\\spam\\alot'])

        self.assertRaises(TypeError, ntpath.commonpath,
                          [b'C:\\Program Files', 'C:\\Program Files\\Foo'])
        self.assertRaises(TypeError, ntpath.commonpath,
                          [b'C:\\Program Files', 'Program Files\\Foo'])
        self.assertRaises(TypeError, ntpath.commonpath,
                          [b'Program Files', 'C:\\Program Files\\Foo'])
        self.assertRaises(TypeError, ntpath.commonpath,
                          ['C:\\Program Files', b'C:\\Program Files\\Foo'])
        self.assertRaises(TypeError, ntpath.commonpath,
                          ['C:\\Program Files', b'Program Files\\Foo'])
        self.assertRaises(TypeError, ntpath.commonpath,
                          ['Program Files', b'C:\\Program Files\\Foo'])

    def test_sameopenfile(self):
        with TemporaryFile() as tf1, TemporaryFile() as tf2:
            # Make sure the same file is really the same
            self.assertTrue(ntpath.sameopenfile(tf1.fileno(), tf1.fileno()))
            # Make sure different files are really different
            self.assertFalse(ntpath.sameopenfile(tf1.fileno(), tf2.fileno()))
            # Make sure invalid values don't cause issues on win32
            if sys.platform == "win32":
                with self.assertRaises(OSError):
                    # Invalid file descriptors shouldn't display assert
                    # dialogs (#4804)
                    ntpath.sameopenfile(-1, -1)

    # TODO: RUSTPYTHON
    if sys.platform == "win32":
        test_sameopenfile = unittest.expectedFailure(test_sameopenfile)

    def test_ismount(self):
        self.assertTrue(ntpath.ismount("c:\\"))
        self.assertTrue(ntpath.ismount("C:\\"))
        self.assertTrue(ntpath.ismount("c:/"))
        self.assertTrue(ntpath.ismount("C:/"))
        self.assertTrue(ntpath.ismount("\\\\.\\c:\\"))
        self.assertTrue(ntpath.ismount("\\\\.\\C:\\"))

        self.assertTrue(ntpath.ismount(b"c:\\"))
        self.assertTrue(ntpath.ismount(b"C:\\"))
        self.assertTrue(ntpath.ismount(b"c:/"))
        self.assertTrue(ntpath.ismount(b"C:/"))
        self.assertTrue(ntpath.ismount(b"\\\\.\\c:\\"))
        self.assertTrue(ntpath.ismount(b"\\\\.\\C:\\"))

        with os_helper.temp_dir() as d:
            self.assertFalse(ntpath.ismount(d))

        if sys.platform == "win32":
            #
            # Make sure the current folder isn't the root folder
            # (or any other volume root). The drive-relative
            # locations below cannot then refer to mount points
            #
            drive, path = ntpath.splitdrive(sys.executable)
            with os_helper.change_cwd(ntpath.dirname(sys.executable)):
                self.assertFalse(ntpath.ismount(drive.lower()))
                self.assertFalse(ntpath.ismount(drive.upper()))

            self.assertTrue(ntpath.ismount("\\\\localhost\\c$"))
            self.assertTrue(ntpath.ismount("\\\\localhost\\c$\\"))

            self.assertTrue(ntpath.ismount(b"\\\\localhost\\c$"))
            self.assertTrue(ntpath.ismount(b"\\\\localhost\\c$\\"))

    def assertEqualCI(self, s1, s2):
        """Assert that two strings are equal ignoring case differences."""
        self.assertEqual(s1.lower(), s2.lower())

    @unittest.skipUnless(nt, "OS helpers require 'nt' module")
    def test_nt_helpers(self):
        # Trivial validation that the helpers do not break, and support both
        # unicode and bytes (UTF-8) paths

        executable = nt._getfinalpathname(sys.executable)

        for path in executable, os.fsencode(executable):
            volume_path = nt._getvolumepathname(path)
            path_drive = ntpath.splitdrive(path)[0]
            volume_path_drive = ntpath.splitdrive(volume_path)[0]
            self.assertEqualCI(path_drive, volume_path_drive)

        cap, free = nt._getdiskusage(sys.exec_prefix)
        self.assertGreater(cap, 0)
        self.assertGreater(free, 0)
        b_cap, b_free = nt._getdiskusage(sys.exec_prefix.encode())
        # Free space may change, so only test the capacity is equal
        self.assertEqual(b_cap, cap)
        self.assertGreater(b_free, 0)

        for path in [sys.prefix, sys.executable]:
            final_path = nt._getfinalpathname(path)
            self.assertIsInstance(final_path, str)
            self.assertGreater(len(final_path), 0)

            b_final_path = nt._getfinalpathname(path.encode())
            self.assertIsInstance(b_final_path, bytes)
            self.assertGreater(len(b_final_path), 0)