# CAU: Adaptation of the cpython 2.2 test_array.py for jython 2.2
#      Formerly test_jarray.py, now test_array.py so that this 
#      test completely supercedes the cpthyhon test.  It would
#      be better to simply complement the cpython test, but that
#      test bombs out too early due to basic incompatibilities.
#
#      The jarray module is being phased out, with all functionality
#      now available in the array module.

from test_support import *
from array import array, zeros
import sys
from java.lang import String
from java.lang.reflect import Array
from java.util import Arrays

print_test('array module (test_array.py)', 1)

def main():
   
    test_jarray() # while it's still supported
   
    test_java_compat()
    test_java_object_arrays()

    testtype('c', 'c')
    for type in (['b', 'h', 'i', 'l', 'f', 'd']):
        testtype(type, 1)
      
    #test a mix of known success and failure cases
    init_tests()
    extend_tests()
    fromlist_tests()

    unlink(TESTFN)

def test_jarray(): # until it is fully formally removed

   # While jarray is still being phased out, just flex the initilaizers.
   # The rest of the test for array will catch all the big problems.
   import jarray
   jarray.array(range(5), 'i')
   jarray.array([String("a"), String("b"), String("c")], String)
   jarray.zeros(5, 'i')
   jarray.zeros(5, String)


def test_java_object_arrays():
   jStringArr = array(String, [String("a"), String("b"), String("c")])
   verify(Arrays.equals(jStringArr.typecode, str(String)), 
         "String array typecode of wrong type, expected %s, found %s" % 
         (jStringArr.typecode, str(String)))
   verify(zeros(String, 5) == Array.newInstance(String, 5))

   import java # require for eval to work
   if jStringArr != eval(str(jStringArr)):
      raise TestFailed, "eval(str(%s)) <> %s" % (jStringArr,)*2
   

def test_java_compat():
   print_test('array', 2)
   from java import awt
   hsb = awt.Color.RGBtoHSB(0,255,255, None)
   #print hsb
   verify(hsb == array('f', [0.5,1,1]), 
         "output hsb float array does not correspond to input rgb values")
   
   rgb = apply(awt.Color.HSBtoRGB, tuple(hsb))
   #print hex(rgb)
   verify(rgb == 0xff00ffff, "output rgb bytes don't match input hsb floats")
   
   print_test('zeros', 2)
   hsb1 = zeros('f', 3)
   awt.Color.RGBtoHSB(0,255,255, hsb1)
   #print hsb, hsb1
   verify(hsb == hsb1, "hsb float arrays were not equal")

def testoverflow(type, lowerLimit, upperLimit):
        # should not overflow assigning lower limit
    if verbose:
        print "test overflow: array(%s, [%s])" % (lowerLimit, type)
    try:
        a = array(type, [lowerLimit])
    except:
        raise TestFailed("array(%s) overflowed assigning %s" %
                (lowerLimit, type))
    # should overflow assigning less than lower limit
    if verbose:
        print "test overflow: array(%s, [%s])" % (lowerLimit-1, type)
    try:
        a = array(type, [lowerLimit-1])
        raise TestFailed, "array(%s) did not overflow assigning %s" %\
                (lowerLimit-1, type)
    except OverflowError:
        pass
    # should not overflow assigning upper limit
    if verbose:
        print "test verflow: array(%s, [%s])" % (upperLimit, type)
    try:
        a = array(type, [upperLimit])
    except:
        raise TestFailed, "array(%s) overflowed assigning %s" %\
                (upperLimit, type)
    # should overflow assigning more than upper limit
    if verbose:
        print "test overflow: array(%s, [%s])" % (upperLimit+1, type)
    try:
        a = array(type, [upperLimit+1])
        raise TestFailed, "array(%s) did not overflow assigning %s" %\
                (upperLimit+1, type)
    except OverflowError:
        pass


def testtype(type, example):

    if verbose:
       print "testing type ", type

    a = array(type)
    a.append(example)
    if verbose:
        print 40*'*'
        print 'array after append: ', a
    a.typecode
    a.itemsize
    
    if a <> eval(str(a)):
       raise TestFailed, "eval(str(%s)) <> %s" % (a,a)

    if a.typecode in ('i', 'b', 'h', 'l'):
        a.byteswap()

    if a.typecode == 'c':
        f = open(TESTFN, "w")
        f.write("The quick brown fox jumps over the lazy dog.\n")
        f.close()
        f = open(TESTFN, 'r')
        a.fromfile(f, 10)
        f.close()
        if verbose:
            print 'char array with 10 bytes of TESTFN appended: ', a
        a.fromlist(['a', 'b', 'c'])
        if verbose:
            print 'char array with list appended: ', a

    a.insert(0, example)
    if verbose:
        print 'array of %s after inserting another:' % a.typecode, a
    f = open(TESTFN, 'w')
    a.tofile(f)
    f.close()

    # This block is just to verify that the operations don't blow up.
    a.tolist()
    a.tostring()
    repr(a)
    str(a)

    if verbose:
        print 'array of %s converted to a list: ' % a.typecode, a.tolist()
    if verbose:
        print 'array of %s converted to a string: ' \
               % a.typecode, a.tostring()

    if type == 'c':
        a = array(type, "abcde")
        a[:-1] = a
        if a != array(type, "abcdee"):
            raise TestFailed, "array(%s) self-slice-assign (head)" % type
        a = array(type, "abcde")
        a[1:] = a
        if a != array(type, "aabcde"):
            raise TestFailed, "array(%s) self-slice-assign (tail)" % type
        a = array(type, "abcde")
        a[1:-1] = a
        if a != array(type, "aabcdee"):
            raise TestFailed, "array(%s) self-slice-assign (cntr)" % type
        if a.index("e") != 5:
            raise TestFailed, "array(%s) index-test" % type
        if a.count("a") != 2:
            raise TestFailed, "array(%s) count-test" % type
        a.remove("e")