예제 #1
0
def test_init():
    # note that we try to ONLY test init here when possible, so we do things like comparing data attributes to a list

    # constructing using both args and kwargs here should give us the same result
    assert ([1, 2, 3] == 
        Vector(1, 2, 3).data ==
        Vector(x=1, y=2, z=3).data ==
        Vector(1, z=3, y=2).data)
    
    # same as kwargs, but tests that skipped-over places are filled with 0s
    assert Vector(z=4, w=2).data == [0, 0, 4, 2]

    # now we try a few combinations of creating a vector from some iterable
    assert ([1, 2, 3] ==
        Vector([1, 2, 3]).data ==
        Vector(iter([1, 2, 3])).data ==
        Vector.from_iter([1, 2, 3]).data == 
        Vector.from_iter(iter([1, 2, 3])).data)

    # now check from_size construction
    from_size = Vector.from_size(2)
    assert from_size.data == [0, 0]
    assert Vector.from_size(5, fill=42).data == [42, 42, 42, 42, 42]

    # try connecting a bunch of things together
    from_connect = Vector(from_size, 1, Vector(1, 2), [3, 5])
    assert from_connect.data == [0, 0, 1, 1, 2, 3, 5]

    # verify that from_size wasn't somehow mutated in the process
    assert from_size.data == [0, 0]

    # now lets create some vectors using from_polar
    from_polar = Vector.from_polar(42, math.pi, 0, 0)
    from_polar_3d_units = [
        Vector.from_polar(1, 0, 0), # Vector(1, 0, 0)
        Vector.from_polar(1, math.pi/2, 0), # Vector(0, 1, 0)
        Vector.from_polar(1, math.pi/2, math.pi/2) # Vector(0, 0, 1)
    ]
    
    # we won't get very accurate results, so we need to check aproximate equality
    assert all(map(aprox_equal, from_polar.data, [-42, 0, 0, 0]))

    for dim, unit in enumerate(from_polar_3d_units):
        correct_unit = Vector.from_size(3).data
        correct_unit[dim] = 1
        assert all(map(aprox_equal, unit.data, correct_unit))
예제 #2
0
def init_vs_from_iter():
    init_list = [1, 2, 3]
    print("__init__:", timeit(lambda: Vector(init_list)))
    print("from_iter:", timeit(lambda: Vector.from_iter(init_list)))