diff options
| author | Simon Hausmann <simon.hausmann@nokia.com> | 2012-01-06 14:44:00 +0100 |
|---|---|---|
| committer | Simon Hausmann <simon.hausmann@nokia.com> | 2012-01-06 14:44:00 +0100 |
| commit | 40736c5763bf61337c8c14e16d8587db021a87d4 (patch) | |
| tree | b17a9c00042ad89cb1308e2484491799aa14e9f8 /Tools/TestWebKitAPI/Tests | |
| download | qtwebkit-40736c5763bf61337c8c14e16d8587db021a87d4.tar.gz | |
Imported WebKit commit 2ea9d364d0f6efa8fa64acf19f451504c59be0e4 (http://svn.webkit.org/repository/webkit/trunk@104285)
Diffstat (limited to 'Tools/TestWebKitAPI/Tests')
85 files changed, 7082 insertions, 0 deletions
diff --git a/Tools/TestWebKitAPI/Tests/TestWebKitAPI/mac/InstanceMethodSwizzler.mm b/Tools/TestWebKitAPI/Tests/TestWebKitAPI/mac/InstanceMethodSwizzler.mm new file mode 100644 index 000000000..f869272ea --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/TestWebKitAPI/mac/InstanceMethodSwizzler.mm @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#import "config.h" +#import "InstanceMethodSwizzler.h" + +#import <wtf/RetainPtr.h> + +@interface SimpleObject : NSObject +- (void)setValue:(int*)value; +@end + +@implementation SimpleObject +- (void)setValue:(int*)value +{ + *value = 1; +} +@end + +namespace TestWebKitAPI { + +static void setValue2(id self, SEL _cmd, int* value) +{ + *value = 2; +} + +static void setValue3(id self, SEL _cmd, int* value) +{ + *value = 3; +} + +TEST(TestWebKitAPI, InstanceMethodSwizzler) +{ + RetainPtr<SimpleObject> object(AdoptNS, [[SimpleObject alloc] init]); + + int value = 0; + + [object.get() setValue:&value]; + EXPECT_EQ(value, 1); + + { + InstanceMethodSwizzler swizzle([object.get() class], @selector(setValue:), reinterpret_cast<IMP>(setValue2)); + + [object.get() setValue:&value]; + EXPECT_EQ(value, 2); + + { + InstanceMethodSwizzler swizzle([object.get() class], @selector(setValue:), reinterpret_cast<IMP>(setValue3)); + + [object.get() setValue:&value]; + EXPECT_EQ(value, 3); + } + + [object.get() setValue:&value]; + EXPECT_EQ(value, 2); + } + + [object.get() setValue:&value]; + EXPECT_EQ(value, 1); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WTF/CheckedArithmeticOperations.cpp b/Tools/TestWebKitAPI/Tests/WTF/CheckedArithmeticOperations.cpp new file mode 100644 index 000000000..768c7d3af --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WTF/CheckedArithmeticOperations.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include <wtf/CheckedArithmetic.h> + +namespace TestWebKitAPI { + +#define CheckedArithmeticTest(type, coerceLiteral, MixedSignednessTest) \ + TEST(WTF, Checked_##type) \ + { \ + Checked<type, RecordOverflow> value; \ + EXPECT_EQ(coerceLiteral(0), value.unsafeGet()); \ + EXPECT_EQ(std::numeric_limits<type>::max(), (value + std::numeric_limits<type>::max()).unsafeGet()); \ + EXPECT_EQ(std::numeric_limits<type>::max(), (std::numeric_limits<type>::max() + value).unsafeGet()); \ + EXPECT_EQ(std::numeric_limits<type>::min(), (value + std::numeric_limits<type>::min()).unsafeGet()); \ + EXPECT_EQ(std::numeric_limits<type>::min(), (std::numeric_limits<type>::min() + value).unsafeGet()); \ + EXPECT_EQ(coerceLiteral(0), (value * coerceLiteral(0)).unsafeGet()); \ + EXPECT_EQ(coerceLiteral(0), (coerceLiteral(0) * value).unsafeGet()); \ + EXPECT_EQ(coerceLiteral(0), (value * value).unsafeGet()); \ + EXPECT_EQ(coerceLiteral(0), (value - coerceLiteral(0)).unsafeGet()); \ + EXPECT_EQ(coerceLiteral(0), (coerceLiteral(0) - value).unsafeGet()); \ + EXPECT_EQ(coerceLiteral(0), (value - value).unsafeGet()); \ + EXPECT_EQ(coerceLiteral(0), (value++).unsafeGet()); \ + EXPECT_EQ(coerceLiteral(1), (value--).unsafeGet()); \ + EXPECT_EQ(coerceLiteral(1), (++value).unsafeGet()); \ + EXPECT_EQ(coerceLiteral(0), (--value).unsafeGet()); \ + EXPECT_EQ(coerceLiteral(10), (value += coerceLiteral(10)).unsafeGet()); \ + EXPECT_EQ(coerceLiteral(10), value.unsafeGet()); \ + EXPECT_EQ(coerceLiteral(100), (value *= coerceLiteral(10)).unsafeGet()); \ + EXPECT_EQ(coerceLiteral(100), value.unsafeGet()); \ + EXPECT_EQ(coerceLiteral(0), (value -= coerceLiteral(100)).unsafeGet()); \ + EXPECT_EQ(coerceLiteral(0), value.unsafeGet()); \ + value = 10; \ + EXPECT_EQ(coerceLiteral(10), value.unsafeGet()); \ + EXPECT_EQ(coerceLiteral(0), (value - coerceLiteral(10)).unsafeGet()); \ + EXPECT_EQ(coerceLiteral(10), value.unsafeGet()); \ + value = std::numeric_limits<type>::min(); \ + EXPECT_EQ(true, (Checked<type, RecordOverflow>(value - coerceLiteral(1))).hasOverflowed()); \ + EXPECT_EQ(true, !((value--).hasOverflowed())); \ + EXPECT_EQ(true, value.hasOverflowed()); \ + value = std::numeric_limits<type>::max(); \ + EXPECT_EQ(true, !value.hasOverflowed()); \ + EXPECT_EQ(true, (Checked<type, RecordOverflow>(value + coerceLiteral(1))).hasOverflowed()); \ + EXPECT_EQ(true, !(value++).hasOverflowed()); \ + EXPECT_EQ(true, value.hasOverflowed()); \ + value = std::numeric_limits<type>::max(); \ + EXPECT_EQ(true, (value += coerceLiteral(1)).hasOverflowed()); \ + EXPECT_EQ(true, value.hasOverflowed()); \ + value = 10; \ + MixedSignednessTest(EXPECT_EQ(coerceLiteral(0), (value + -10).unsafeGet())); \ + MixedSignednessTest(EXPECT_EQ(0U, (value - 10U).unsafeGet())); \ + MixedSignednessTest(EXPECT_EQ(coerceLiteral(0), (-10 + value).unsafeGet())); \ + MixedSignednessTest(EXPECT_EQ(0U, (10U - value).unsafeGet())); \ + value = std::numeric_limits<type>::min(); \ + MixedSignednessTest(EXPECT_EQ(true, (Checked<type, RecordOverflow>(value - 1)).hasOverflowed())); \ + MixedSignednessTest(EXPECT_EQ(true, !(value--).hasOverflowed())); \ + MixedSignednessTest(EXPECT_EQ(true, value.hasOverflowed())); \ + value = std::numeric_limits<type>::max(); \ + MixedSignednessTest(EXPECT_EQ(true, !value.hasOverflowed())); \ + MixedSignednessTest(EXPECT_EQ(true, (Checked<type, RecordOverflow>(value + 1)).hasOverflowed())); \ + MixedSignednessTest(EXPECT_EQ(true, !(value++).hasOverflowed())); \ + MixedSignednessTest(EXPECT_EQ(true, value.hasOverflowed())); \ + value = std::numeric_limits<type>::max(); \ + MixedSignednessTest(EXPECT_EQ(true, (value += 1).hasOverflowed())); \ + MixedSignednessTest(EXPECT_EQ(true, value.hasOverflowed())); \ + value = std::numeric_limits<type>::min(); \ + MixedSignednessTest(EXPECT_EQ(true, (value - 1U).hasOverflowed())); \ + MixedSignednessTest(EXPECT_EQ(true, !(value--).hasOverflowed())); \ + MixedSignednessTest(EXPECT_EQ(true, value.hasOverflowed())); \ + value = std::numeric_limits<type>::max(); \ + MixedSignednessTest(EXPECT_EQ(true, !value.hasOverflowed())); \ + MixedSignednessTest(EXPECT_EQ(true, (Checked<type, RecordOverflow>(value + 1U)).hasOverflowed())); \ + MixedSignednessTest(EXPECT_EQ(true, !(value++).hasOverflowed())); \ + MixedSignednessTest(EXPECT_EQ(true, value.hasOverflowed())); \ + value = std::numeric_limits<type>::max(); \ + MixedSignednessTest(EXPECT_EQ(true, (value += 1U).hasOverflowed())); \ + MixedSignednessTest(EXPECT_EQ(true, value.hasOverflowed())); \ + } + +#define CoerceLiteralToUnsigned(x) x##U +#define CoerceLiteralNop(x) x +#define AllowMixedSignednessTest(x) x +#define IgnoreMixedSignednessTest(x) +CheckedArithmeticTest(int8_t, CoerceLiteralNop, IgnoreMixedSignednessTest) +CheckedArithmeticTest(int16_t, CoerceLiteralNop, IgnoreMixedSignednessTest) +CheckedArithmeticTest(int32_t, CoerceLiteralNop, AllowMixedSignednessTest) +CheckedArithmeticTest(uint32_t, CoerceLiteralToUnsigned, AllowMixedSignednessTest) +CheckedArithmeticTest(int64_t, CoerceLiteralNop, IgnoreMixedSignednessTest) +CheckedArithmeticTest(uint64_t, CoerceLiteralToUnsigned, IgnoreMixedSignednessTest) + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WTF/Functional.cpp b/Tools/TestWebKitAPI/Tests/WTF/Functional.cpp new file mode 100644 index 000000000..cf8c3c39c --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WTF/Functional.cpp @@ -0,0 +1,218 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include <wtf/RefCounted.h> +#include <wtf/Functional.h> + +namespace TestWebKitAPI { + +static int returnFortyTwo() +{ + return 42; +} + +TEST(FunctionalTest, Basic) +{ + Function<int ()> emptyFunction; + ASSERT_TRUE(emptyFunction.isNull()); + + Function<int ()> returnFortyTwoFunction = bind(returnFortyTwo); + ASSERT_FALSE(returnFortyTwoFunction.isNull()); + ASSERT_EQ(42, returnFortyTwoFunction()); +} + +static int multiplyByTwo(int n) +{ + return n * 2; +} + +static double multiplyByOneAndAHalf(double d) +{ + return d * 1.5; +} + +TEST(FunctionalTest, UnaryBind) +{ + Function<int ()> multiplyFourByTwoFunction = bind(multiplyByTwo, 4); + ASSERT_EQ(8, multiplyFourByTwoFunction()); + + Function<double ()> multiplyByOneAndAHalfFunction = bind(multiplyByOneAndAHalf, 3); + ASSERT_EQ(4.5, multiplyByOneAndAHalfFunction()); +} + +static int multiply(int x, int y) +{ + return x * y; +} + +static int subtract(int x, int y) +{ + return x - y; +} + +TEST(FunctionalTest, BinaryBind) +{ + Function<int ()> multiplyFourByTwoFunction = bind(multiply, 4, 2); + ASSERT_EQ(8, multiplyFourByTwoFunction()); + + Function<int ()> subtractTwoFromFourFunction = bind(subtract, 4, 2); + ASSERT_EQ(2, subtractTwoFromFourFunction()); +} + +class A { +public: + explicit A(int i) + : m_i(i) + { + } + + int f() { return m_i; } + int addF(int j) { return m_i + j; } + +private: + int m_i; +}; + +TEST(FunctionalTest, MemberFunctionBind) +{ + A a(10); + Function<int ()> function1 = bind(&A::f, &a); + ASSERT_EQ(10, function1()); + + Function<int ()> function2 = bind(&A::addF, &a, 15); + ASSERT_EQ(25, function2()); +} + +class B { +public: + B() + : m_numRefCalls(0) + , m_numDerefCalls(0) + { + } + + ~B() + { + } + + void ref() + { + m_numRefCalls++; + } + + void deref() + { + m_numDerefCalls++; + } + + void f() { ASSERT_GT(m_numRefCalls, 0); } + void g(int) { ASSERT_GT(m_numRefCalls, 0); } + + int m_numRefCalls; + int m_numDerefCalls; +}; + +TEST(FunctionalTest, MemberFunctionBindRefDeref) +{ + B b; + + { + Function<void ()> function1 = bind(&B::f, &b); + function1(); + + Function<void ()> function2 = bind(&B::g, &b, 10); + function2(); + } + + ASSERT_TRUE(b.m_numRefCalls == b.m_numDerefCalls); + ASSERT_GT(b.m_numRefCalls, 0); + +} + +class Number : public RefCounted<Number> { +public: + static PassRefPtr<Number> create(int value) + { + return adoptRef(new Number(value)); + } + + ~Number() + { + m_value = 0; + } + + int value() const { return m_value; } + +private: + explicit Number(int value) + : m_value(value) + { + } + + int m_value; +}; + +static int multiplyNumberByTwo(Number* number) +{ + return number->value() * 2; +} + +TEST(FunctionalTest, RefCountedStorage) +{ + RefPtr<Number> five = Number::create(5); + Function<int ()> multiplyFiveByTwoFunction = bind(multiplyNumberByTwo, five); + ASSERT_EQ(10, multiplyFiveByTwoFunction()); + + Function<int ()> multiplyFourByTwoFunction = bind(multiplyNumberByTwo, Number::create(4)); + ASSERT_EQ(8, multiplyFourByTwoFunction()); + + RefPtr<Number> six = Number::create(6); + Function<int ()> multiplySixByTwoFunction = bind(multiplyNumberByTwo, six.release()); + ASSERT_FALSE(six); + ASSERT_EQ(12, multiplySixByTwoFunction()); +} + +namespace RefAndDerefTests { + + template<typename T> struct RefCounted { + void ref(); + void deref(); + }; + struct Connection : RefCounted<Connection> { }; + COMPILE_ASSERT(WTF::HasRefAndDeref<Connection>::value, class_has_ref_and_deref); + + struct NoRefOrDeref { }; + COMPILE_ASSERT(!WTF::HasRefAndDeref<NoRefOrDeref>::value, class_has_no_ref_or_deref); + + struct RefOnly { void ref(); }; + COMPILE_ASSERT(!WTF::HasRefAndDeref<RefOnly>::value, class_has_ref_only); + + struct DerefOnly { void deref(); }; + COMPILE_ASSERT(!WTF::HasRefAndDeref<DerefOnly>::value, class_has_deref_only); + +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WTF/HashMap.cpp b/Tools/TestWebKitAPI/Tests/WTF/HashMap.cpp new file mode 100644 index 000000000..b9f4c1fdd --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WTF/HashMap.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2011 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#include <wtf/HashMap.h> + +namespace TestWebKitAPI { + +typedef WTF::HashMap<int, int> IntHashMap; + +TEST(WTF, HashTableIteratorComparison) +{ + IntHashMap map; + map.add(1, 2); + ASSERT_TRUE(map.begin() != map.end()); + ASSERT_FALSE(map.begin() == map.end()); + + IntHashMap::const_iterator begin = map.begin(); + ASSERT_TRUE(begin == map.begin()); + ASSERT_TRUE(map.begin() == begin); + ASSERT_TRUE(begin != map.end()); + ASSERT_TRUE(map.end() != begin); + ASSERT_FALSE(begin != map.begin()); + ASSERT_FALSE(map.begin() != begin); + ASSERT_FALSE(begin == map.end()); + ASSERT_FALSE(map.end() == begin); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WTF/MetaAllocator.cpp b/Tools/TestWebKitAPI/Tests/WTF/MetaAllocator.cpp new file mode 100644 index 000000000..4de523a3b --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WTF/MetaAllocator.cpp @@ -0,0 +1,953 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include <stdarg.h> +#include <wtf/MetaAllocator.h> +#include <wtf/Vector.h> + +using namespace WTF; + +namespace TestWebKitAPI { + +class MetaAllocatorTest: public testing::Test { +public: + enum SanityCheckMode { RunSanityCheck, DontRunSanityCheck }; + + enum HeapGrowthMode { DontGrowHeap, ForTestDemandAllocCoalesce, ForTestDemandAllocDontCoalesce }; + + HeapGrowthMode currentHeapGrowthMode; + size_t allowAllocatePages; + size_t requestedNumPages; + + class SimpleTestAllocator: public MetaAllocator { + public: + SimpleTestAllocator(MetaAllocatorTest* parent) + : MetaAllocator(32) + , m_parent(parent) + { + addFreshFreeSpace(reinterpret_cast<void*>(basePage * pageSize()), defaultPagesInHeap * pageSize()); + } + + virtual ~SimpleTestAllocator() + { + EXPECT_TRUE(!m_parent->allocatorDestroyed); + m_parent->allocatorDestroyed = true; + } + + virtual void* allocateNewSpace(size_t& numPages) + { + switch (m_parent->currentHeapGrowthMode) { + case DontGrowHeap: + return 0; + + case ForTestDemandAllocCoalesce: + case ForTestDemandAllocDontCoalesce: { + EXPECT_TRUE(m_parent->allowAllocatePages); + EXPECT_TRUE(m_parent->allowAllocatePages >= numPages); + m_parent->requestedNumPages = numPages; + numPages = m_parent->allowAllocatePages; + + unsigned offset; + if (m_parent->currentHeapGrowthMode == ForTestDemandAllocCoalesce) + offset = 0; + else + offset = 1; + + void* result = reinterpret_cast<void*>((basePage + defaultPagesInHeap + offset) * pageSize()); + + m_parent->allowAllocatePages = 0; + m_parent->currentHeapGrowthMode = DontGrowHeap; + + for (size_t counter = 0; counter < numPages + offset; ++counter) { + m_parent->pageMap->append(false); + for (unsigned byteCounter = 0; byteCounter < pageSize(); ++byteCounter) + m_parent->memoryMap->append(false); + } + + m_parent->additionalPagesInHeap += numPages; + + return result; + } + + default: + CRASH(); + return 0; + } + } + + virtual void notifyNeedPage(void* page) + { + // the page should be both free and unmapped. + EXPECT_TRUE(!m_parent->pageState(reinterpret_cast<uintptr_t>(page) / pageSize())); + for (uintptr_t address = reinterpret_cast<uintptr_t>(page); address < reinterpret_cast<uintptr_t>(page) + pageSize(); ++address) + EXPECT_TRUE(!m_parent->byteState(reinterpret_cast<void*>(address))); + m_parent->pageState(reinterpret_cast<uintptr_t>(page) / pageSize()) = true; + } + + virtual void notifyPageIsFree(void* page) + { + // the page should be free of objects at this point, but it should still + // be mapped. + EXPECT_TRUE(m_parent->pageState(reinterpret_cast<uintptr_t>(page) / pageSize())); + for (uintptr_t address = reinterpret_cast<uintptr_t>(page); address < reinterpret_cast<uintptr_t>(page) + pageSize(); ++address) + EXPECT_TRUE(!m_parent->byteState(reinterpret_cast<void*>(address))); + m_parent->pageState(reinterpret_cast<uintptr_t>(page) / pageSize()) = false; + } + + private: + MetaAllocatorTest* m_parent; + }; + + static const unsigned basePage = 1; + static const unsigned defaultPagesInHeap = 100; + + unsigned additionalPagesInHeap; + + Vector<bool, 0>* memoryMap; + Vector<bool, 0>* pageMap; + bool allocatorDestroyed; + + SimpleTestAllocator* allocator; + + virtual void SetUp() + { + memoryMap = new Vector<bool, 0>(); + pageMap = new Vector<bool, 0>(); + + for (unsigned page = basePage; page < basePage + defaultPagesInHeap; ++page) { + pageMap->append(false); + for (unsigned byteInPage = 0; byteInPage < pageSize(); ++byteInPage) + memoryMap->append(false); + } + + allocatorDestroyed = false; + + currentHeapGrowthMode = DontGrowHeap; + allowAllocatePages = 0; + additionalPagesInHeap = 0; + requestedNumPages = 0; + + allocator = new SimpleTestAllocator(this); + } + + virtual void TearDown() + { + EXPECT_TRUE(currentHeapGrowthMode == DontGrowHeap); + EXPECT_EQ(allowAllocatePages, static_cast<size_t>(0)); + EXPECT_EQ(requestedNumPages, static_cast<size_t>(0)); + + // memory should be free. + for (unsigned page = basePage; page < basePage + defaultPagesInHeap; ++page) { + EXPECT_TRUE(!pageState(page)); + for (unsigned byteInPage = 0; byteInPage < pageSize(); ++byteInPage) + EXPECT_TRUE(!byteState(page * pageSize() + byteInPage)); + } + + // NOTE: this automatically tests that the allocator did not leak + // memory, so long as these tests are running with !defined(NDEBUG). + // See MetaAllocator::m_mallocBalance. + delete allocator; + + EXPECT_TRUE(allocatorDestroyed); + + delete memoryMap; + delete pageMap; + } + + MetaAllocatorHandle* allocate(size_t sizeInBytes, SanityCheckMode sanityCheckMode = RunSanityCheck) + { + MetaAllocatorHandle* handle = allocator->allocate(sizeInBytes).leakRef(); + EXPECT_TRUE(handle); + EXPECT_EQ(handle->sizeInBytes(), sizeInBytes); + + uintptr_t startByte = reinterpret_cast<uintptr_t>(handle->start()); + uintptr_t endByte = startByte + sizeInBytes; + for (uintptr_t currentByte = startByte; currentByte < endByte; ++currentByte) { + EXPECT_TRUE(!byteState(currentByte)); + byteState(currentByte) = true; + EXPECT_TRUE(pageState(currentByte / pageSize())); + } + + if (sanityCheckMode == RunSanityCheck) + sanityCheck(); + + return handle; + } + + void free(MetaAllocatorHandle* handle, SanityCheckMode sanityCheckMode = RunSanityCheck) + { + EXPECT_TRUE(handle); + + notifyFree(handle->start(), handle->sizeInBytes()); + handle->deref(); + + if (sanityCheckMode == RunSanityCheck) + sanityCheck(); + } + + void notifyFree(void* start, size_t sizeInBytes) + { + uintptr_t startByte = reinterpret_cast<uintptr_t>(start); + uintptr_t endByte = startByte + sizeInBytes; + for (uintptr_t currentByte = startByte; currentByte < endByte; ++currentByte) { + EXPECT_TRUE(byteState(currentByte)); + byteState(currentByte) = false; + } + } + + void sanityCheck() + { +#ifndef NDEBUG + EXPECT_EQ(allocator->bytesReserved() - allocator->bytesAllocated(), allocator->debugFreeSpaceSize()); +#endif + EXPECT_EQ(allocator->bytesReserved(), (defaultPagesInHeap + additionalPagesInHeap) * pageSize()); + EXPECT_EQ(allocator->bytesAllocated(), bytesAllocated()); + EXPECT_EQ(allocator->bytesCommitted(), bytesCommitted()); + } + + void confirm(MetaAllocatorHandle* handle) + { + uintptr_t startByte = reinterpret_cast<uintptr_t>(handle->start()); + confirm(startByte, startByte + handle->sizeInBytes(), true); + } + + void confirmHighWatermark(MetaAllocatorHandle* handle) + { + confirm(reinterpret_cast<uintptr_t>(handle->end()), (basePage + defaultPagesInHeap) * pageSize(), false); + } + + void confirm(uintptr_t startByte, uintptr_t endByte, bool value) + { + for (uintptr_t currentByte = startByte; currentByte < endByte; ++currentByte) { + EXPECT_EQ(byteState(currentByte), value); + if (value) + EXPECT_TRUE(pageState(currentByte / pageSize())); + } + if (!value) { + uintptr_t firstFreePage = (startByte + pageSize() - 1) / pageSize(); + uintptr_t lastFreePage = (endByte - pageSize()) / pageSize(); + for (uintptr_t currentPage = firstFreePage; currentPage <= lastFreePage; ++currentPage) + EXPECT_TRUE(!pageState(currentPage)); + } + } + + size_t bytesAllocated() + { + size_t result = 0; + for (unsigned index = 0; index < memoryMap->size(); ++index) { + if (memoryMap->at(index)) + result++; + } + return result; + } + + size_t bytesCommitted() + { + size_t result = 0; + for (unsigned index = 0; index < pageMap->size(); ++index) { + if (pageMap->at(index)) + result++; + } + return result * pageSize(); + } + + bool& byteState(void* address) + { + return byteState(reinterpret_cast<uintptr_t>(address)); + } + + bool& byteState(uintptr_t address) + { + uintptr_t byteIndex = address - basePage * pageSize(); + return memoryMap->at(byteIndex); + } + + bool& pageState(uintptr_t page) + { + uintptr_t pageIndex = page - basePage; + return pageMap->at(pageIndex); + } + + // Test helpers + + void testOneAlloc(size_t size) + { + // Tests the most basic behavior: allocate one thing and free it. Also + // verifies that the state of pages is correct. + + MetaAllocatorHandle* handle = allocate(size); + EXPECT_EQ(handle->start(), reinterpret_cast<void*>(basePage * pageSize())); + EXPECT_EQ(handle->sizeInBytes(), size); + EXPECT_TRUE(pageState(basePage)); + + confirm(handle); + confirmHighWatermark(handle); + + free(handle); + } + + void testRepeatAllocFree(size_t firstSize, ...) + { + // Tests right-coalescing by repeatedly allocating and freeing. The idea + // is that if you allocate something and then free it, then the heap should + // look identical to what it was before the allocation due to a right-coalesce + // of the freed chunk and the already-free memory, and so subsequent + // allocations should behave the same as the first one. + + MetaAllocatorHandle* handle = allocate(firstSize); + EXPECT_EQ(handle->start(), reinterpret_cast<void*>(basePage * pageSize())); + EXPECT_EQ(handle->sizeInBytes(), firstSize); + + confirm(handle); + confirmHighWatermark(handle); + + free(handle); + + va_list argList; + va_start(argList, firstSize); + while (size_t sizeInBytes = va_arg(argList, int)) { + handle = allocate(sizeInBytes); + EXPECT_EQ(handle->start(), reinterpret_cast<void*>(basePage * pageSize())); + EXPECT_EQ(handle->sizeInBytes(), sizeInBytes); + + confirm(handle); + confirmHighWatermark(handle); + + free(handle); + } + va_end(argList); + } + + void testSimpleFullCoalesce(size_t firstSize, size_t secondSize, size_t thirdSize) + { + // Allocates something of size firstSize, then something of size secondSize, and then + // frees the first allocation, and then the second, and then attempts to allocate the + // third, asserting that it allocated at the base address of the heap. + + // Note that this test may cause right-allocation, which will cause the test to fail. + // Thus the correct way of running this test is to ensure that secondSize is + // picked in such a way that it never straddles a page. + + MetaAllocatorHandle* firstHandle = allocate(firstSize); + EXPECT_EQ(firstHandle->start(), reinterpret_cast<void*>(basePage * pageSize())); + EXPECT_EQ(firstHandle->sizeInBytes(), firstSize); + + confirm(firstHandle); + confirmHighWatermark(firstHandle); + + MetaAllocatorHandle* secondHandle = allocate(secondSize); + EXPECT_EQ(secondHandle->start(), reinterpret_cast<void*>(basePage * pageSize() + firstSize)); + EXPECT_EQ(secondHandle->sizeInBytes(), secondSize); + + confirm(firstHandle); + confirm(secondHandle); + confirmHighWatermark(secondHandle); + + free(firstHandle); + + confirm(secondHandle); + confirmHighWatermark(secondHandle); + + free(secondHandle); + + confirm(basePage * pageSize(), (basePage + defaultPagesInHeap) * pageSize(), false); + + MetaAllocatorHandle* thirdHandle = allocate(thirdSize); + EXPECT_EQ(thirdHandle->start(), reinterpret_cast<void*>(basePage * pageSize())); + EXPECT_EQ(thirdHandle->sizeInBytes(), thirdSize); + + confirm(thirdHandle); + confirmHighWatermark(thirdHandle); + + free(thirdHandle); + } + + enum TestFIFOAllocMode { FillAtEnd, EagerFill }; + void testFIFOAlloc(TestFIFOAllocMode mode, ...) + { + // This will test the simple case of no-coalesce (freeing the left-most + // chunk in memory when the chunk to the right of it is allocated) and + // fully exercise left-coalescing and full-coalescing. In EagerFill + // mode, this also tests perfect-fit allocation and no-coalescing free. + + size_t totalSize = 0; + + Vector<MetaAllocatorHandle*, 0> handles; + + va_list argList; + va_start(argList, mode); + while (size_t sizeInBytes = va_arg(argList, int)) { + MetaAllocatorHandle* handle = allocate(sizeInBytes); + EXPECT_EQ(handle->start(), reinterpret_cast<void*>(basePage * pageSize() + totalSize)); + EXPECT_EQ(handle->sizeInBytes(), sizeInBytes); + + confirm(handle); + confirmHighWatermark(handle); + + handles.append(handle); + totalSize += sizeInBytes; + } + va_end(argList); + + for (unsigned index = 0; index < handles.size(); ++index) + confirm(handles.at(index)); + + size_t sizeSoFar = 0; + for (unsigned index = 0; index < handles.size(); ++index) { + sizeSoFar += handles.at(index)->sizeInBytes(); + free(handles.at(index)); + if (mode == EagerFill) { + MetaAllocatorHandle* handle = allocate(sizeSoFar); + EXPECT_EQ(handle->start(), reinterpret_cast<void*>(basePage * pageSize())); + EXPECT_EQ(handle->sizeInBytes(), sizeSoFar); + + confirm(basePage * pageSize(), basePage * pageSize() + totalSize, true); + if (index < handles.size() - 1) + confirmHighWatermark(handles.last()); + else + confirmHighWatermark(handle); + + free(handle); + + confirm(basePage * pageSize(), basePage * pageSize() + sizeSoFar, false); + } + } + + ASSERT(sizeSoFar == totalSize); + + confirm(basePage * pageSize(), (basePage + defaultPagesInHeap) * pageSize(), false); + + if (mode == FillAtEnd) { + MetaAllocatorHandle* finalHandle = allocate(totalSize); + EXPECT_EQ(finalHandle->start(), reinterpret_cast<void*>(basePage * pageSize())); + EXPECT_EQ(finalHandle->sizeInBytes(), totalSize); + + confirm(finalHandle); + confirmHighWatermark(finalHandle); + + free(finalHandle); + } + } + + void testFillHeap(size_t sizeInBytes, size_t numAllocations) + { + Vector<MetaAllocatorHandle*, 0> handles; + + for (size_t index = 0; index < numAllocations; ++index) + handles.append(allocate(sizeInBytes, DontRunSanityCheck)); + + sanityCheck(); + + EXPECT_TRUE(!allocator->allocate(sizeInBytes)); + + for (size_t index = 0; index < numAllocations; ++index) + free(handles.at(index), DontRunSanityCheck); + + sanityCheck(); + } + + void testRightAllocation(size_t firstLeftSize, size_t firstRightSize, size_t secondLeftSize, size_t secondRightSize) + { + MetaAllocatorHandle* firstLeft = allocate(firstLeftSize); + EXPECT_EQ(firstLeft->start(), reinterpret_cast<void*>(basePage * pageSize())); + + MetaAllocatorHandle* firstRight = allocate(firstRightSize); + EXPECT_EQ(firstRight->end(), reinterpret_cast<void*>((basePage + defaultPagesInHeap) * pageSize())); + + MetaAllocatorHandle* secondLeft = allocate(secondLeftSize); + EXPECT_EQ(secondLeft->start(), reinterpret_cast<void*>(basePage * pageSize() + firstLeft->sizeInBytes())); + + MetaAllocatorHandle* secondRight = allocate(secondRightSize); + EXPECT_EQ(secondRight->end(), reinterpret_cast<void*>((basePage + defaultPagesInHeap) * pageSize() - firstRight->sizeInBytes())); + + free(firstLeft); + free(firstRight); + free(secondLeft); + free(secondRight); + + MetaAllocatorHandle* final = allocate(defaultPagesInHeap * pageSize()); + EXPECT_EQ(final->start(), reinterpret_cast<void*>(basePage * pageSize())); + + free(final); + } + + void testBestFit(size_t firstSize, size_t step, unsigned numSlots, SanityCheckMode sanityCheckMode) + { + Vector<MetaAllocatorHandle*, 0> handlesToFree; + Vector<MetaAllocatorHandle*, 0> handles; + Vector<void*, 0> locations; + + size_t size = firstSize; + for (unsigned index = 0; index < numSlots; ++index) { + MetaAllocatorHandle* toFree = allocate(size, sanityCheckMode); + if (!handles.isEmpty()) { + while (toFree->start() != handles.last()->end()) { + handlesToFree.append(toFree); + toFree = allocate(size, sanityCheckMode); + } + } + + MetaAllocatorHandle* fragger = allocate(32, sanityCheckMode); + EXPECT_EQ(fragger->start(), toFree->end()); + + locations.append(toFree->start()); + + handlesToFree.append(toFree); + handles.append(fragger); + + size += step; + } + + ASSERT(locations.size() == numSlots); + + for (unsigned index = 0; index < handlesToFree.size(); ++index) + free(handlesToFree.at(index), sanityCheckMode); + + size = firstSize; + for (unsigned index = 0; index < numSlots; ++index) { + MetaAllocatorHandle* bestFit = allocate(size - 32, sanityCheckMode); + + EXPECT_TRUE(bestFit->start() == locations.at(index) + || bestFit->end() == reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(locations.at(index)) + size)); + + MetaAllocatorHandle* small = allocate(32, sanityCheckMode); + if (bestFit->start() == locations.at(index)) + EXPECT_EQ(small->start(), bestFit->end()); + else + EXPECT_EQ(small->end(), bestFit->start()); + + free(bestFit, sanityCheckMode); + free(small, sanityCheckMode); + + size += step; + } + + for (unsigned index = 0; index < numSlots; ++index) + free(handles.at(index), sanityCheckMode); + + MetaAllocatorHandle* final = allocate(defaultPagesInHeap * pageSize(), sanityCheckMode); + EXPECT_EQ(final->start(), reinterpret_cast<void*>(basePage * pageSize())); + + free(final, sanityCheckMode); + } + + void testShrink(size_t firstSize, size_t secondSize) + { + // Allocate the thing that will be shrunk + MetaAllocatorHandle* handle = allocate(firstSize); + + // Shrink it, and make sure that our state reflects the shrinkage. + notifyFree(reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(handle->start()) + secondSize), firstSize - secondSize); + + handle->shrink(secondSize); + EXPECT_EQ(handle->sizeInBytes(), secondSize); + + sanityCheck(); + + // Assert that the heap is not empty. + EXPECT_TRUE(!allocator->allocate(defaultPagesInHeap * pageSize())); + + // Allocate the remainder of the heap. + MetaAllocatorHandle* remainder = allocate(defaultPagesInHeap * pageSize() - secondSize); + EXPECT_EQ(remainder->start(), handle->end()); + + free(remainder); + free(handle); + + // Assert that the heap is empty and finish up. + MetaAllocatorHandle* final = allocate(defaultPagesInHeap * pageSize()); + EXPECT_EQ(final->start(), reinterpret_cast<void*>(basePage * pageSize())); + + free(final); + } + + void testDemandAllocCoalesce(size_t firstSize, size_t numPages, size_t secondSize) + { + EXPECT_TRUE(!allocator->allocate((defaultPagesInHeap + numPages) * pageSize())); + + MetaAllocatorHandle* firstHandle = allocate(firstSize); + + EXPECT_TRUE(!allocator->allocate(secondSize)); + EXPECT_TRUE(!allocator->allocate((defaultPagesInHeap + numPages) * pageSize())); + + currentHeapGrowthMode = ForTestDemandAllocCoalesce; + allowAllocatePages = numPages; + + MetaAllocatorHandle* secondHandle = allocate(secondSize); + + EXPECT_TRUE(currentHeapGrowthMode == DontGrowHeap); + EXPECT_EQ(allowAllocatePages, static_cast<size_t>(0)); + EXPECT_EQ(requestedNumPages, (secondSize + pageSize() - 1) / pageSize()); + EXPECT_EQ(secondHandle->start(), reinterpret_cast<void*>((basePage + defaultPagesInHeap) * pageSize())); + + requestedNumPages = 0; + + free(firstHandle); + free(secondHandle); + + free(allocate((defaultPagesInHeap + numPages) * pageSize())); + } + + void testDemandAllocDontCoalesce(size_t firstSize, size_t numPages, size_t secondSize) + { + free(allocate(firstSize)); + free(allocate(defaultPagesInHeap * pageSize())); + EXPECT_TRUE(!allocator->allocate((defaultPagesInHeap + numPages) * pageSize())); + + MetaAllocatorHandle* firstHandle = allocate(firstSize); + + EXPECT_TRUE(!allocator->allocate(secondSize)); + EXPECT_TRUE(!allocator->allocate((defaultPagesInHeap + numPages) * pageSize())); + + currentHeapGrowthMode = ForTestDemandAllocDontCoalesce; + allowAllocatePages = numPages; + + MetaAllocatorHandle* secondHandle = allocate(secondSize); + + EXPECT_TRUE(currentHeapGrowthMode == DontGrowHeap); + EXPECT_EQ(allowAllocatePages, static_cast<size_t>(0)); + EXPECT_EQ(requestedNumPages, (secondSize + pageSize() - 1) / pageSize()); + EXPECT_EQ(secondHandle->start(), reinterpret_cast<void*>((basePage + defaultPagesInHeap + 1) * pageSize())); + + requestedNumPages = 0; + + EXPECT_TRUE(!allocator->allocate((defaultPagesInHeap + numPages) * pageSize())); + + free(firstHandle); + free(secondHandle); + + EXPECT_TRUE(!allocator->allocate((defaultPagesInHeap + numPages) * pageSize())); + + firstHandle = allocate(firstSize); + secondHandle = allocate(secondSize); + EXPECT_EQ(firstHandle->start(), reinterpret_cast<void*>(basePage * pageSize())); + EXPECT_EQ(secondHandle->start(), reinterpret_cast<void*>((basePage + defaultPagesInHeap + 1) * pageSize())); + free(firstHandle); + free(secondHandle); + } +}; + +TEST_F(MetaAllocatorTest, Empty) +{ + // Tests that creating and destroying an allocator works. +} + +TEST_F(MetaAllocatorTest, AllocZero) +{ + // Tests that allocating a zero-length block returns 0 and + // does not change anything in memory. + + ASSERT(!allocator->allocate(0)); + + MetaAllocatorHandle* final = allocate(defaultPagesInHeap * pageSize()); + EXPECT_EQ(final->start(), reinterpret_cast<void*>(basePage * pageSize())); + free(final); +} + +TEST_F(MetaAllocatorTest, OneAlloc32) +{ + testOneAlloc(32); +} + +TEST_F(MetaAllocatorTest, OneAlloc64) +{ + testOneAlloc(64); +} + +TEST_F(MetaAllocatorTest, OneAllocTwoPages) +{ + testOneAlloc(pageSize() * 2); +} + +TEST_F(MetaAllocatorTest, RepeatAllocFree32Twice) +{ + testRepeatAllocFree(32, 32, 0); +} + +TEST_F(MetaAllocatorTest, RepeatAllocFree32Then64) +{ + testRepeatAllocFree(32, 64, 0); +} + +TEST_F(MetaAllocatorTest, RepeatAllocFree64Then32) +{ + testRepeatAllocFree(64, 32, 0); +} + +TEST_F(MetaAllocatorTest, RepeatAllocFree32TwiceThen64) +{ + testRepeatAllocFree(32, 32, 64, 0); +} + +TEST_F(MetaAllocatorTest, RepeatAllocFree32Then64Twice) +{ + testRepeatAllocFree(32, 64, 64, 0); +} + +TEST_F(MetaAllocatorTest, RepeatAllocFree64Then32Then64) +{ + testRepeatAllocFree(64, 32, 64, 0); +} + +TEST_F(MetaAllocatorTest, RepeatAllocFree32Thrice) +{ + testRepeatAllocFree(32, 32, 32, 0); +} + +TEST_F(MetaAllocatorTest, RepeatAllocFree32Then64Then32) +{ + testRepeatAllocFree(32, 32, 32, 0); +} + +TEST_F(MetaAllocatorTest, RepeatAllocFree64Then32Twice) +{ + testRepeatAllocFree(64, 32, 32, 0); +} + +TEST_F(MetaAllocatorTest, RepeatAllocFreeTwoPagesThen32) +{ + testRepeatAllocFree(static_cast<int>(pageSize() * 2), 32, 0); +} + +TEST_F(MetaAllocatorTest, RepeatAllocFree32ThenTwoPages) +{ + testRepeatAllocFree(32, static_cast<int>(pageSize() * 2), 0); +} + +TEST_F(MetaAllocatorTest, RepeatAllocFreePageThenTwoPages) +{ + testRepeatAllocFree(static_cast<int>(pageSize()), static_cast<int>(pageSize() * 2), 0); +} + +TEST_F(MetaAllocatorTest, RepeatAllocFreeTwoPagesThenPage) +{ + testRepeatAllocFree(static_cast<int>(pageSize() * 2), static_cast<int>(pageSize()), 0); +} + +TEST_F(MetaAllocatorTest, SimpleFullCoalesce32Plus32Then128) +{ + testSimpleFullCoalesce(32, 32, 128); +} + +TEST_F(MetaAllocatorTest, SimpleFullCoalesce32Plus64Then128) +{ + testSimpleFullCoalesce(32, 64, 128); +} + +TEST_F(MetaAllocatorTest, SimpleFullCoalesce64Plus32Then128) +{ + testSimpleFullCoalesce(64, 32, 128); +} + +TEST_F(MetaAllocatorTest, SimpleFullCoalesce32PlusPageLess32ThenPage) +{ + testSimpleFullCoalesce(32, pageSize() - 32, pageSize()); +} + +TEST_F(MetaAllocatorTest, SimpleFullCoalesce32PlusPageLess32ThenTwoPages) +{ + testSimpleFullCoalesce(32, pageSize() - 32, pageSize() * 2); +} + +TEST_F(MetaAllocatorTest, SimpleFullCoalescePagePlus32ThenTwoPages) +{ + testSimpleFullCoalesce(pageSize(), 32, pageSize() * 2); +} + +TEST_F(MetaAllocatorTest, SimpleFullCoalescePagePlusPageThenTwoPages) +{ + testSimpleFullCoalesce(pageSize(), pageSize(), pageSize() * 2); +} + +TEST_F(MetaAllocatorTest, FIFOAllocFillAtEnd32Twice) +{ + testFIFOAlloc(FillAtEnd, 32, 32, 0); +} + +TEST_F(MetaAllocatorTest, FIFOAllocFillAtEnd32Thrice) +{ + testFIFOAlloc(FillAtEnd, 32, 32, 32, 0); +} + +TEST_F(MetaAllocatorTest, FIFOAllocFillAtEnd32FourTimes) +{ + testFIFOAlloc(FillAtEnd, 32, 32, 32, 32, 0); +} + +TEST_F(MetaAllocatorTest, FIFOAllocFillAtEndPageLess32Then32ThenPageLess64Then64) +{ + testFIFOAlloc(FillAtEnd, static_cast<int>(pageSize() - 32), 32, static_cast<int>(pageSize() - 64), 64, 0); +} + +TEST_F(MetaAllocatorTest, FIFOAllocEagerFill32Twice) +{ + testFIFOAlloc(EagerFill, 32, 32, 0); +} + +TEST_F(MetaAllocatorTest, FIFOAllocEagerFill32Thrice) +{ + testFIFOAlloc(EagerFill, 32, 32, 32, 0); +} + +TEST_F(MetaAllocatorTest, FIFOAllocEagerFill32FourTimes) +{ + testFIFOAlloc(EagerFill, 32, 32, 32, 32, 0); +} + +TEST_F(MetaAllocatorTest, FIFOAllocEagerFillPageLess32Then32ThenPageLess64Then64) +{ + testFIFOAlloc(EagerFill, static_cast<int>(pageSize() - 32), 32, static_cast<int>(pageSize() - 64), 64, 0); +} + +TEST_F(MetaAllocatorTest, FillHeap32) +{ + testFillHeap(32, defaultPagesInHeap * pageSize() / 32); +} + +TEST_F(MetaAllocatorTest, FillHeapPage) +{ + testFillHeap(pageSize(), defaultPagesInHeap); +} + +TEST_F(MetaAllocatorTest, FillHeapTwoPages) +{ + testFillHeap(pageSize() * 2, defaultPagesInHeap / 2); +} + +TEST_F(MetaAllocatorTest, RightAllocation32ThenPageThen32ThenPage) +{ + testRightAllocation(32, pageSize(), 32, pageSize()); +} + +TEST_F(MetaAllocatorTest, RightAllocationQuarterPageThenPageThenQuarterPageThenPage) +{ + testRightAllocation(pageSize() / 4, pageSize(), pageSize() / 4, pageSize()); +} + +TEST_F(MetaAllocatorTest, BestFit64Plus64Thrice) +{ + testBestFit(64, 64, 3, RunSanityCheck); +} + +TEST_F(MetaAllocatorTest, BestFit64Plus64TenTimes) +{ + testBestFit(64, 64, 10, DontRunSanityCheck); +} + +TEST_F(MetaAllocatorTest, BestFit64Plus64HundredTimes) +{ + testBestFit(64, 64, 100, DontRunSanityCheck); +} + +TEST_F(MetaAllocatorTest, BestFit96Plus64Thrice) +{ + testBestFit(96, 64, 3, RunSanityCheck); +} + +TEST_F(MetaAllocatorTest, BestFit96Plus64TenTimes) +{ + testBestFit(96, 64, 10, DontRunSanityCheck); +} + +TEST_F(MetaAllocatorTest, BestFit96Plus64HundredTimes) +{ + testBestFit(96, 64, 100, DontRunSanityCheck); +} + +TEST_F(MetaAllocatorTest, BestFit96Plus96Thrice) +{ + testBestFit(96, 96, 3, RunSanityCheck); +} + +TEST_F(MetaAllocatorTest, BestFit96Plus96TenTimes) +{ + testBestFit(96, 96, 10, DontRunSanityCheck); +} + +TEST_F(MetaAllocatorTest, BestFit96Plus96EightyTimes) +{ + testBestFit(96, 96, 80, DontRunSanityCheck); +} + +TEST_F(MetaAllocatorTest, Shrink64To32) +{ + testShrink(64, 32); +} + +TEST_F(MetaAllocatorTest, ShrinkPageTo32) +{ + testShrink(pageSize(), 32); +} + +TEST_F(MetaAllocatorTest, ShrinkPageToPageLess32) +{ + testShrink(pageSize(), pageSize() - 32); +} + +TEST_F(MetaAllocatorTest, ShrinkTwoPagesTo32) +{ + testShrink(pageSize() * 2, 32); +} + +TEST_F(MetaAllocatorTest, ShrinkTwoPagesToPagePlus32) +{ + testShrink(pageSize() * 2, pageSize() + 32); +} + +TEST_F(MetaAllocatorTest, ShrinkTwoPagesToPage) +{ + testShrink(pageSize() * 2, pageSize()); +} + +TEST_F(MetaAllocatorTest, ShrinkTwoPagesToPageLess32) +{ + testShrink(pageSize() * 2, pageSize() - 32); +} + +TEST_F(MetaAllocatorTest, ShrinkTwoPagesToTwoPagesLess32) +{ + testShrink(pageSize() * 2, pageSize() * 2 - 32); +} + +TEST_F(MetaAllocatorTest, DemandAllocCoalescePageThenDoubleHeap) +{ + testDemandAllocCoalesce(pageSize(), defaultPagesInHeap, defaultPagesInHeap * pageSize()); +} + +TEST_F(MetaAllocatorTest, DemandAllocCoalescePageThenTripleHeap) +{ + testDemandAllocCoalesce(pageSize(), defaultPagesInHeap * 2, defaultPagesInHeap * pageSize()); +} + +TEST_F(MetaAllocatorTest, DemandAllocDontCoalescePageThenDoubleHeap) +{ + testDemandAllocDontCoalesce(pageSize(), defaultPagesInHeap, defaultPagesInHeap * pageSize()); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WTF/RedBlackTree.cpp b/Tools/TestWebKitAPI/Tests/WTF/RedBlackTree.cpp new file mode 100644 index 000000000..efac240ab --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WTF/RedBlackTree.cpp @@ -0,0 +1,305 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include <wtf/RedBlackTree.h> +#include <wtf/Vector.h> + +using namespace WTF; + +namespace TestWebKitAPI { + +class RedBlackTreeTest: public testing::Test { +public: + unsigned m_counter; + + virtual void SetUp() + { + m_counter = 0; + } + + virtual void TearDown() + { + } + + struct Pair { + char key; + unsigned value; + + Pair() { } + + Pair(char key, unsigned value) + : key(key) + , value(value) + { + } + + bool operator==(const Pair& other) const + { + return key == other.key; + } + + bool operator<(const Pair& other) const + { + return key < other.key; + } + }; + + typedef Vector<Pair, 16> PairVector; + + PairVector findExact(PairVector& asVector, char key) + { + PairVector result; + + for (size_t index = 0; index < asVector.size(); ++index) { + if (asVector.at(index).key == key) + result.append(asVector.at(index)); + } + + std::sort(result.begin(), result.end()); + + return result; + } + + void remove(PairVector& asVector, size_t index) + { + asVector.at(index) = asVector.last(); + asVector.removeLast(); + } + + PairVector findLeastGreaterThanOrEqual(PairVector& asVector, char key) + { + char bestKey = 0; // assignment to make gcc happy + bool foundKey = false; + + for (size_t index = 0; index < asVector.size(); ++index) { + if (asVector.at(index).key >= key) { + if (asVector.at(index).key < bestKey || !foundKey) { + foundKey = true; + bestKey = asVector.at(index).key; + } + } + } + + PairVector result; + + if (!foundKey) + return result; + + return findExact(asVector, bestKey); + } + + void assertFoundAndRemove(PairVector& asVector, char key, unsigned value) + { + bool found = false; + size_t foundIndex = 0; // make compilers happy + + for (size_t index = 0; index < asVector.size(); ++index) { + if (asVector.at(index).key == key + && asVector.at(index).value == value) { + EXPECT_TRUE(!found); + + found = true; + foundIndex = index; + } + } + + EXPECT_TRUE(found); + + remove(asVector, foundIndex); + } + + // This deliberately passes a copy of the vector. + void assertEqual(RedBlackTree<char, unsigned>& asTree, PairVector asVector) + { + for (RedBlackTree<char, unsigned>::Node* current = asTree.first(); current; current = current->successor()) + assertFoundAndRemove(asVector, current->m_key, current->m_value); + } + + void assertSameValuesForKey(RedBlackTree<char, unsigned>& asTree, RedBlackTree<char, unsigned>::Node* node, PairVector foundValues, char key) + { + if (node) { + EXPECT_EQ(node->m_key, key); + + RedBlackTree<char, unsigned>::Node* prevNode = node; + do { + node = prevNode; + prevNode = prevNode->predecessor(); + } while (prevNode && prevNode->m_key == key); + + EXPECT_EQ(node->m_key, key); + EXPECT_TRUE(!prevNode || prevNode->m_key < key); + + do { + assertFoundAndRemove(foundValues, node->m_key, node->m_value); + + node = node->successor(); + EXPECT_TRUE(!node || node->m_key >= key); + } while (node && node->m_key == key); + } + + EXPECT_TRUE(foundValues.isEmpty()); + } + + // The control string is a null-terminated list of commands. Each + // command is two characters, with the first identifying the operation + // and the second giving a key. The commands are: + // +x Add x + // *x Find all elements equal to x + // @x Find all elements that have the smallest key that is greater than or equal to x + // !x Remove all elements equal to x + void testDriver(const char* controlString) + { + PairVector asVector; + RedBlackTree<char, unsigned> asTree; + + for (const char* current = controlString; *current; current += 2) { + char command = current[0]; + char key = current[1]; + unsigned value = ++m_counter; + + ASSERT(command); + ASSERT(key); + + switch (command) { + case '+': { + RedBlackTree<char, unsigned>::Node* node = new RedBlackTree<char, unsigned>::Node(key, value); + asTree.insert(node); + asVector.append(Pair(key, value)); + break; + } + + case '*': { + RedBlackTree<char, unsigned>::Node* node = asTree.findExact(key); + if (node) + EXPECT_EQ(node->m_key, key); + assertSameValuesForKey(asTree, node, findExact(asVector, key), key); + break; + } + + case '@': { + RedBlackTree<char, unsigned>::Node* node = asTree.findLeastGreaterThanOrEqual(key); + if (node) { + EXPECT_TRUE(node->m_key >= key); + assertSameValuesForKey(asTree, node, findLeastGreaterThanOrEqual(asVector, key), node->m_key); + } else + EXPECT_TRUE(findLeastGreaterThanOrEqual(asVector, key).isEmpty()); + break; + } + + case '!': { + while (true) { + RedBlackTree<char, unsigned>::Node* node = asTree.remove(key); + if (node) { + EXPECT_EQ(node->m_key, key); + assertFoundAndRemove(asVector, node->m_key, node->m_value); + } else { + EXPECT_TRUE(findExact(asVector, key).isEmpty()); + break; + } + } + break; + } + + default: + ASSERT_NOT_REACHED(); + break; + } + + EXPECT_EQ(asTree.size(), asVector.size()); + assertEqual(asTree, asVector); + } + } +}; + +TEST_F(RedBlackTreeTest, Empty) +{ + testDriver(""); +} + +TEST_F(RedBlackTreeTest, EmptyGetFindRemove) +{ + testDriver("*x@y!z"); +} + +TEST_F(RedBlackTreeTest, SingleAdd) +{ + testDriver("+a"); +} + +TEST_F(RedBlackTreeTest, SingleAddGetFindRemoveNotFound) +{ + testDriver("+a*x@y!z"); +} + +TEST_F(RedBlackTreeTest, SingleAddGetFindRemove) +{ + testDriver("+a*a@a!a"); +} + +TEST_F(RedBlackTreeTest, TwoAdds) +{ + testDriver("+a+b"); +} + +TEST_F(RedBlackTreeTest, ThreeAdds) +{ + testDriver("+a+b+c"); +} + +TEST_F(RedBlackTreeTest, FourAdds) +{ + testDriver("+a+b+c+d"); +} + +TEST_F(RedBlackTreeTest, LotsOfRepeatAdds) +{ + testDriver("+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d"); +} + +TEST_F(RedBlackTreeTest, LotsOfRepeatAndUniqueAdds) +{ + testDriver("+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+r+s+t+u+v+x+y+z"); +} + +TEST_F(RedBlackTreeTest, LotsOfRepeatAndUniqueAddsAndGetsAndRemoves) +{ + testDriver("+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+r+s+t+u+v+x+y+z*a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z!a!b!c!d!e!f!g!h!i!j!k!l!m!n!o!p!q!r!s!t!u!v!w!x!y!z"); +} + +TEST_F(RedBlackTreeTest, SimpleBestFitSearch) +{ + testDriver("+d+d+m+w@d@m@w@a@g@q"); +} + +TEST_F(RedBlackTreeTest, BiggerBestFitSearch) +{ + testDriver("+d+d+d+d+d+d+d+d+d+d+f+f+f+f+f+f+f+h+h+i+j+k+l+m+o+p+q+r+z@a@b@c@d@e@f@g@h@i@j@k@l@m@n@o@p@q@r@s@t@u@v@w@x@y@z"); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WTF/StringBuilder.cpp b/Tools/TestWebKitAPI/Tests/WTF/StringBuilder.cpp new file mode 100644 index 000000000..a968e2aa9 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WTF/StringBuilder.cpp @@ -0,0 +1,201 @@ +/* + * Copyright (C) 2011 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include <wtf/Assertions.h> +#include <wtf/text/CString.h> +#include <wtf/text/StringBuilder.h> +#include <wtf/text/WTFString.h> + +namespace WTF { + +// For EXPECT_EQ(String, String) +std::ostream& operator<<(std::ostream& os, const String& string) +{ + return os << string.utf8().data(); +} + +} + +namespace TestWebKitAPI { + +void expectBuilderContent(const char* expected, const StringBuilder& builder) +{ + // Not using builder.toString() or builder.toStringPreserveCapacity() because they all + // change internal state of builder. + EXPECT_EQ(String(expected), String(builder.characters(), builder.length())); +} + +void expectEmpty(const StringBuilder& builder) +{ + EXPECT_EQ(0U, builder.length()); + EXPECT_TRUE(builder.isEmpty()); + EXPECT_EQ(0, builder.characters()); +} + +TEST(StringBuilderTest, DefaultConstructor) +{ + StringBuilder builder; + expectEmpty(builder); +} + +TEST(StringBuilderTest, Append) +{ + StringBuilder builder; + builder.append(String("0123456789")); + expectBuilderContent("0123456789", builder); + builder.append("abcd"); + expectBuilderContent("0123456789abcd", builder); + builder.append("efgh", 3); + expectBuilderContent("0123456789abcdefg", builder); + builder.append(""); + expectBuilderContent("0123456789abcdefg", builder); + builder.append('#'); + expectBuilderContent("0123456789abcdefg#", builder); + + builder.toString(); // Test after reifyString(). + StringBuilder builder1; + builder.append("", 0); + expectBuilderContent("0123456789abcdefg#", builder); + builder1.append(builder.characters(), builder.length()); + builder1.append("XYZ"); + builder.append(builder1.characters(), builder1.length()); + expectBuilderContent("0123456789abcdefg#0123456789abcdefg#XYZ", builder); +} + +TEST(StringBuilderTest, ToString) +{ + StringBuilder builder; + builder.append("0123456789"); + String string = builder.toString(); + ASSERT_EQ(String("0123456789"), string); + ASSERT_EQ(string.impl(), builder.toString().impl()); + + // Changing the StringBuilder should not affect the original result of toString(). + builder.append("abcdefghijklmnopqrstuvwxyz"); + ASSERT_EQ(String("0123456789"), string); + + // Changing the StringBuilder should not affect the original result of toString() in case the capacity is not changed. + builder.reserveCapacity(200); + string = builder.toString(); + ASSERT_EQ(String("0123456789abcdefghijklmnopqrstuvwxyz"), string); + builder.append("ABC"); + ASSERT_EQ(String("0123456789abcdefghijklmnopqrstuvwxyz"), string); + + // Changing the original result of toString() should not affect the content of the StringBuilder. + String string1 = builder.toString(); + ASSERT_EQ(String("0123456789abcdefghijklmnopqrstuvwxyzABC"), string1); + string1.append("DEF"); + ASSERT_EQ(String("0123456789abcdefghijklmnopqrstuvwxyzABC"), builder.toString()); + ASSERT_EQ(String("0123456789abcdefghijklmnopqrstuvwxyzABCDEF"), string1); + + // Resizing the StringBuilder should not affect the original result of toString(). + string1 = builder.toString(); + builder.resize(10); + builder.append("###"); + ASSERT_EQ(String("0123456789abcdefghijklmnopqrstuvwxyzABC"), string1); +} + +TEST(StringBuilderTest, ToStringPreserveCapacity) +{ + StringBuilder builder; + builder.append("0123456789"); + String string = builder.toStringPreserveCapacity(); + ASSERT_EQ(String("0123456789"), string); + ASSERT_EQ(string.impl(), builder.toStringPreserveCapacity().impl()); + ASSERT_EQ(string.characters(), builder.characters()); + + // Changing the StringBuilder should not affect the original result of toStringPreserveCapacity(). + builder.append("abcdefghijklmnopqrstuvwxyz"); + ASSERT_EQ(String("0123456789"), string); + + // Changing the StringBuilder should not affect the original result of toStringPreserveCapacity() in case the capacity is not changed. + builder.reserveCapacity(200); + string = builder.toStringPreserveCapacity(); + ASSERT_EQ(string.characters(), builder.characters()); + ASSERT_EQ(String("0123456789abcdefghijklmnopqrstuvwxyz"), string); + builder.append("ABC"); + ASSERT_EQ(String("0123456789abcdefghijklmnopqrstuvwxyz"), string); + + // Changing the original result of toStringPreserveCapacity() should not affect the content of the StringBuilder. + String string1 = builder.toStringPreserveCapacity(); + ASSERT_EQ(string1.characters(), builder.characters()); + ASSERT_EQ(String("0123456789abcdefghijklmnopqrstuvwxyzABC"), string1); + string1.append("DEF"); + ASSERT_EQ(String("0123456789abcdefghijklmnopqrstuvwxyzABC"), builder.toStringPreserveCapacity()); + ASSERT_EQ(String("0123456789abcdefghijklmnopqrstuvwxyzABCDEF"), string1); + + // Resizing the StringBuilder should not affect the original result of toStringPreserveCapacity(). + string1 = builder.toStringPreserveCapacity(); + ASSERT_EQ(string.characters(), builder.characters()); + builder.resize(10); + builder.append("###"); + ASSERT_EQ(String("0123456789abcdefghijklmnopqrstuvwxyzABC"), string1); +} + +TEST(StringBuilderTest, Clear) +{ + StringBuilder builder; + builder.append("0123456789"); + builder.clear(); + expectEmpty(builder); +} + +TEST(StringBuilderTest, Array) +{ + StringBuilder builder; + builder.append("0123456789"); + EXPECT_EQ('0', static_cast<char>(builder[0])); + EXPECT_EQ('9', static_cast<char>(builder[9])); + builder.toString(); // Test after reifyString(). + EXPECT_EQ('0', static_cast<char>(builder[0])); + EXPECT_EQ('9', static_cast<char>(builder[9])); +} + +TEST(StringBuilderTest, Resize) +{ + StringBuilder builder; + builder.append("0123456789"); + builder.resize(10); + EXPECT_EQ(10U, builder.length()); + expectBuilderContent("0123456789", builder); + builder.resize(8); + EXPECT_EQ(8U, builder.length()); + expectBuilderContent("01234567", builder); + + builder.toString(); + builder.resize(7); + EXPECT_EQ(7U, builder.length()); + expectBuilderContent("0123456", builder); + builder.resize(0); + expectEmpty(builder); +} + +} // namespace diff --git a/Tools/TestWebKitAPI/Tests/WTF/StringOperators.cpp b/Tools/TestWebKitAPI/Tests/WTF/StringOperators.cpp new file mode 100644 index 000000000..819013fdb --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WTF/StringOperators.cpp @@ -0,0 +1,125 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#define WTF_STRINGTYPEADAPTER_COPIED_WTF_STRING() (++wtfStringCopyCount) + +static int wtfStringCopyCount; + +#include <wtf/text/WTFString.h> + +namespace TestWebKitAPI { + +#define EXPECT_N_WTF_STRING_COPIES(count, expr) \ + do { \ + wtfStringCopyCount = 0; \ + String __testString = expr; \ + (void)__testString; \ + EXPECT_EQ(count, wtfStringCopyCount) << #expr; \ + } while (false) + +TEST(WTF, StringOperators) +{ + String string("String"); + AtomicString atomicString("AtomicString"); + + EXPECT_EQ(0, wtfStringCopyCount); + + EXPECT_N_WTF_STRING_COPIES(2, string + string); + EXPECT_N_WTF_STRING_COPIES(2, string + atomicString); + EXPECT_N_WTF_STRING_COPIES(2, atomicString + string); + EXPECT_N_WTF_STRING_COPIES(2, atomicString + atomicString); + + EXPECT_N_WTF_STRING_COPIES(1, "C string" + string); + EXPECT_N_WTF_STRING_COPIES(1, string + "C string"); + EXPECT_N_WTF_STRING_COPIES(1, "C string" + atomicString); + EXPECT_N_WTF_STRING_COPIES(1, atomicString + "C string"); + + EXPECT_N_WTF_STRING_COPIES(2, "C string" + string + "C string" + string); + EXPECT_N_WTF_STRING_COPIES(2, "C string" + (string + "C string" + string)); + EXPECT_N_WTF_STRING_COPIES(2, ("C string" + string) + ("C string" + string)); + EXPECT_N_WTF_STRING_COPIES(2, string + "C string" + string + "C string"); + EXPECT_N_WTF_STRING_COPIES(2, string + ("C string" + string + "C string")); + EXPECT_N_WTF_STRING_COPIES(2, (string + "C string") + (string + "C string")); + + EXPECT_N_WTF_STRING_COPIES(2, "C string" + atomicString + "C string" + atomicString); + EXPECT_N_WTF_STRING_COPIES(2, "C string" + (atomicString + "C string" + atomicString)); + EXPECT_N_WTF_STRING_COPIES(2, ("C string" + atomicString) + ("C string" + atomicString)); + EXPECT_N_WTF_STRING_COPIES(2, atomicString + "C string" + atomicString + "C string"); + EXPECT_N_WTF_STRING_COPIES(2, atomicString + ("C string" + atomicString + "C string")); + EXPECT_N_WTF_STRING_COPIES(2, (atomicString + "C string") + (atomicString + "C string")); + + EXPECT_N_WTF_STRING_COPIES(2, "C string" + string + "C string" + atomicString); + EXPECT_N_WTF_STRING_COPIES(2, "C string" + (string + "C string" + atomicString)); + EXPECT_N_WTF_STRING_COPIES(2, ("C string" + string) + ("C string" + atomicString)); + EXPECT_N_WTF_STRING_COPIES(2, string + "C string" + atomicString + "C string"); + EXPECT_N_WTF_STRING_COPIES(2, string + ("C string" + atomicString + "C string")); + EXPECT_N_WTF_STRING_COPIES(2, (string + "C string") + (atomicString + "C string")); + + EXPECT_N_WTF_STRING_COPIES(2, "C string" + atomicString + "C string" + string); + EXPECT_N_WTF_STRING_COPIES(2, "C string" + (atomicString + "C string" + string)); + EXPECT_N_WTF_STRING_COPIES(2, ("C string" + atomicString) + ("C string" + string)); + EXPECT_N_WTF_STRING_COPIES(2, atomicString + "C string" + string + "C string"); + EXPECT_N_WTF_STRING_COPIES(2, atomicString + ("C string" + string + "C string")); + EXPECT_N_WTF_STRING_COPIES(2, (atomicString + "C string") + (string + "C string")); + +#if COMPILER(MSVC) + EXPECT_N_WTF_STRING_COPIES(1, L"wide string" + string); + EXPECT_N_WTF_STRING_COPIES(1, string + L"wide string"); + EXPECT_N_WTF_STRING_COPIES(1, L"wide string" + atomicString); + EXPECT_N_WTF_STRING_COPIES(1, atomicString + L"wide string"); + + EXPECT_N_WTF_STRING_COPIES(2, L"wide string" + string + L"wide string" + string); + EXPECT_N_WTF_STRING_COPIES(2, L"wide string" + (string + L"wide string" + string)); + EXPECT_N_WTF_STRING_COPIES(2, (L"wide string" + string) + (L"wide string" + string)); + EXPECT_N_WTF_STRING_COPIES(2, string + L"wide string" + string + L"wide string"); + EXPECT_N_WTF_STRING_COPIES(2, string + (L"wide string" + string + L"wide string")); + EXPECT_N_WTF_STRING_COPIES(2, (string + L"wide string") + (string + L"wide string")); + + EXPECT_N_WTF_STRING_COPIES(2, L"wide string" + atomicString + L"wide string" + atomicString); + EXPECT_N_WTF_STRING_COPIES(2, L"wide string" + (atomicString + L"wide string" + atomicString)); + EXPECT_N_WTF_STRING_COPIES(2, (L"wide string" + atomicString) + (L"wide string" + atomicString)); + EXPECT_N_WTF_STRING_COPIES(2, atomicString + L"wide string" + atomicString + L"wide string"); + EXPECT_N_WTF_STRING_COPIES(2, atomicString + (L"wide string" + atomicString + L"wide string")); + EXPECT_N_WTF_STRING_COPIES(2, (atomicString + L"wide string") + (atomicString + L"wide string")); + + EXPECT_N_WTF_STRING_COPIES(2, L"wide string" + string + L"wide string" + atomicString); + EXPECT_N_WTF_STRING_COPIES(2, L"wide string" + (string + L"wide string" + atomicString)); + EXPECT_N_WTF_STRING_COPIES(2, (L"wide string" + string) + (L"wide string" + atomicString)); + EXPECT_N_WTF_STRING_COPIES(2, string + L"wide string" + atomicString + L"wide string"); + EXPECT_N_WTF_STRING_COPIES(2, string + (L"wide string" + atomicString + L"wide string")); + EXPECT_N_WTF_STRING_COPIES(2, (string + L"wide string") + (atomicString + L"wide string")); + + EXPECT_N_WTF_STRING_COPIES(2, L"wide string" + atomicString + L"wide string" + string); + EXPECT_N_WTF_STRING_COPIES(2, L"wide string" + (atomicString + L"wide string" + string)); + EXPECT_N_WTF_STRING_COPIES(2, (L"wide string" + atomicString) + (L"wide string" + string)); + EXPECT_N_WTF_STRING_COPIES(2, atomicString + L"wide string" + string + L"wide string"); + EXPECT_N_WTF_STRING_COPIES(2, atomicString + (L"wide string" + string + L"wide string")); + EXPECT_N_WTF_STRING_COPIES(2, (atomicString + L"wide string") + (string + L"wide string")); +#endif +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WTF/TemporaryChange.cpp b/Tools/TestWebKitAPI/Tests/WTF/TemporaryChange.cpp new file mode 100644 index 000000000..3ba0f15bd --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WTF/TemporaryChange.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2011 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#include <wtf/TemporaryChange.h> + +namespace TestWebKitAPI { + +TEST(WTF, TemporaryChangeNested) +{ + bool originallyFalse = false; + { + TemporaryChange<bool> change1OriginallyFalse(originallyFalse, true); + EXPECT_TRUE(originallyFalse); + { + TemporaryChange<bool> change2OriginallyFalse(originallyFalse, false); + EXPECT_FALSE(originallyFalse); + } + EXPECT_TRUE(originallyFalse); + } + EXPECT_FALSE(originallyFalse); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WTF/Vector.cpp b/Tools/TestWebKitAPI/Tests/WTF/Vector.cpp new file mode 100644 index 000000000..46a35922f --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WTF/Vector.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include <wtf/Vector.h> + +namespace TestWebKitAPI { + +TEST(WTF_Vector, Iterator) +{ + Vector<int> intVector; + intVector.append(10); + intVector.append(11); + intVector.append(12); + intVector.append(13); + + Vector<int>::iterator it = intVector.begin(); + Vector<int>::iterator end = intVector.end(); + EXPECT_TRUE(end != it); + + EXPECT_EQ(10, *it); + ++it; + EXPECT_EQ(11, *it); + ++it; + EXPECT_EQ(12, *it); + ++it; + EXPECT_EQ(13, *it); + ++it; + + EXPECT_TRUE(end == it); +} + +TEST(WTF_Vector, ReverseIterator) +{ + Vector<int> intVector; + intVector.append(10); + intVector.append(11); + intVector.append(12); + intVector.append(13); + + Vector<int>::reverse_iterator it = intVector.rbegin(); + Vector<int>::reverse_iterator end = intVector.rend(); + EXPECT_TRUE(end != it); + + EXPECT_EQ(13, *it); + ++it; + EXPECT_EQ(12, *it); + ++it; + EXPECT_EQ(11, *it); + ++it; + EXPECT_EQ(10, *it); + ++it; + + EXPECT_TRUE(end == it); +} + +TEST(WTF_Vector, ReversedProxy) +{ + Vector<int> intVector; + intVector.append(10); + intVector.append(11); + intVector.append(12); + intVector.append(13); + + Vector<int>::reverse_iterator it = intVector.reversed().begin(); + Vector<int>::reverse_iterator end = intVector.reversed().end(); + + EXPECT_TRUE(end != it); + + EXPECT_EQ(13, *it); + ++it; + EXPECT_EQ(12, *it); + ++it; + EXPECT_EQ(11, *it); + ++it; + EXPECT_EQ(10, *it); + ++it; + + EXPECT_TRUE(end == it); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WTF/VectorBasic.cpp b/Tools/TestWebKitAPI/Tests/WTF/VectorBasic.cpp new file mode 100644 index 000000000..211ef8841 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WTF/VectorBasic.cpp @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include <wtf/Vector.h> + +namespace TestWebKitAPI { + +TEST(WTF, VectorBasic) +{ + Vector<int> intVector; + EXPECT_TRUE(intVector.isEmpty()); + EXPECT_EQ(0ul, intVector.size()); + EXPECT_EQ(0ul, intVector.capacity()); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WTF/VectorReverse.cpp b/Tools/TestWebKitAPI/Tests/WTF/VectorReverse.cpp new file mode 100644 index 000000000..6d4a00f0f --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WTF/VectorReverse.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include <wtf/Vector.h> + +namespace TestWebKitAPI { + +TEST(WTF, VectorReverse) +{ + Vector<int> intVector; + intVector.append(10); + intVector.append(11); + intVector.append(12); + intVector.append(13); + intVector.reverse(); + + EXPECT_EQ(13, intVector[0]); + EXPECT_EQ(12, intVector[1]); + EXPECT_EQ(11, intVector[2]); + EXPECT_EQ(10, intVector[3]); + + intVector.append(9); + intVector.reverse(); + + EXPECT_EQ(9, intVector[0]); + EXPECT_EQ(10, intVector[1]); + EXPECT_EQ(11, intVector[2]); + EXPECT_EQ(12, intVector[3]); + EXPECT_EQ(13, intVector[4]); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WTF/cf/RetainPtr.cpp b/Tools/TestWebKitAPI/Tests/WTF/cf/RetainPtr.cpp new file mode 100644 index 000000000..0ca174cea --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WTF/cf/RetainPtr.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#include <wtf/RetainPtr.h> + +namespace TestWebKitAPI { + +TEST(RetainPtr, AdoptCF) +{ + RetainPtr<CFStringRef> foo = adoptCF(CFStringCreateWithCString(kCFAllocatorDefault, "foo", kCFStringEncodingUTF8)); + + EXPECT_EQ(1, CFGetRetainCount(foo.get())); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WTF/cf/RetainPtrHashing.cpp b/Tools/TestWebKitAPI/Tests/WTF/cf/RetainPtrHashing.cpp new file mode 100644 index 000000000..0cd28c9bb --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WTF/cf/RetainPtrHashing.cpp @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#include <wtf/HashSet.h> +#include <wtf/HashMap.h> +#include <wtf/RetainPtr.h> + +namespace TestWebKitAPI { + +TEST(RetainPtrHashing, HashSet) +{ + HashSet<RetainPtr<CFStringRef> > set; + + RetainPtr<CFStringRef> foo(AdoptCF, CFStringCreateWithCString(kCFAllocatorDefault, "foo", kCFStringEncodingUTF8)); + + EXPECT_FALSE(set.contains(foo)); + set.add(foo); + EXPECT_TRUE(set.contains(foo)); + + RetainPtr<CFStringRef> foo2(AdoptCF, CFStringCreateWithCString(kCFAllocatorDefault, "foo", kCFStringEncodingUTF8)); + EXPECT_FALSE(set.contains(foo2)); + set.add(foo2); + EXPECT_TRUE(set.contains(foo2)); + + set.remove(foo); + EXPECT_FALSE(set.contains(foo)); +} + +TEST(RetainPtrHashing, HashMapKey) +{ + HashMap<RetainPtr<CFStringRef>, int> map; + + RetainPtr<CFStringRef> foo(AdoptCF, CFStringCreateWithCString(kCFAllocatorDefault, "foo", kCFStringEncodingUTF8)); + + EXPECT_FALSE(map.contains(foo)); + map.add(foo, 1); + EXPECT_EQ(1, map.get(foo)); + + RetainPtr<CFStringRef> foo2(AdoptCF, CFStringCreateWithCString(kCFAllocatorDefault, "foo", kCFStringEncodingUTF8)); + EXPECT_FALSE(map.contains(foo2)); + map.add(foo2, 2); + EXPECT_EQ(2, map.get(foo2)); + + map.remove(foo); + EXPECT_FALSE(map.contains(foo)); +} + +TEST(RetainPtrHashing, HashMapValue) +{ + HashMap<int, RetainPtr<CFStringRef> > map; + + RetainPtr<CFStringRef> foo(AdoptCF, CFStringCreateWithCString(kCFAllocatorDefault, "foo", kCFStringEncodingUTF8)); + + EXPECT_FALSE(map.contains(1)); + map.add(1, foo); + EXPECT_EQ(foo, map.get(1)); + + RetainPtr<CFStringRef> foo2(AdoptCF, CFStringCreateWithCString(kCFAllocatorDefault, "foo", kCFStringEncodingUTF8)); + EXPECT_FALSE(map.contains(2)); + map.add(2, foo2); + EXPECT_EQ(foo2, map.get(2)); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WTF/ns/RetainPtr.mm b/Tools/TestWebKitAPI/Tests/WTF/ns/RetainPtr.mm new file mode 100644 index 000000000..a03971c57 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WTF/ns/RetainPtr.mm @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#include <wtf/RetainPtr.h> + +namespace TestWebKitAPI { + +TEST(RetainPtr, AdoptNS) +{ + RetainPtr<NSObject> foo = adoptNS([[NSObject alloc] init]); + + EXPECT_EQ(1, CFGetRetainCount(foo.get())); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit/win/WebViewDestruction.cpp b/Tools/TestWebKitAPI/Tests/WebKit/win/WebViewDestruction.cpp new file mode 100644 index 000000000..3e6630f98 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit/win/WebViewDestruction.cpp @@ -0,0 +1,178 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#include "HostWindow.h" +#include "Test.h" +#include <WebCore/COMPtr.h> +#include <WebKit/WebKit.h> +#include <WebKit/WebKitCOMAPI.h> +#include <wtf/PassOwnPtr.h> + +namespace TestWebKitAPI { + +template <typename T> +static HRESULT WebKitCreateInstance(REFCLSID clsid, T** object) +{ + return WebKitCreateInstance(clsid, 0, __uuidof(T), reinterpret_cast<void**>(object)); +} + +class WebViewDestruction : public ::testing::Test { +protected: + virtual void SetUp(); + virtual void TearDown(); + + static int webViewCount(); + static void runMessagePump(DWORD timeoutMilliseconds); + + COMPtr<IWebView> m_webView; +}; + +class WebViewDestructionWithHostWindow : public WebViewDestruction { +protected: + virtual void SetUp(); + virtual void TearDown(); + + HostWindow m_window; + HWND m_viewWindow; +}; + +void WebViewDestruction::SetUp() +{ + EXPECT_HRESULT_SUCCEEDED(WebKitCreateInstance(__uuidof(WebView), &m_webView)); +} + +int WebViewDestruction::webViewCount() +{ + COMPtr<IWebKitStatistics> statistics; + if (FAILED(WebKitCreateInstance(__uuidof(WebKitStatistics), &statistics))) + return -1; + int count; + if (FAILED(statistics->webViewCount(&count))) + return -1; + return count; +} + +void WebViewDestructionWithHostWindow::SetUp() +{ + WebViewDestruction::SetUp(); + + EXPECT_TRUE(m_window.initialize()); + EXPECT_HRESULT_SUCCEEDED(m_webView->setHostWindow(reinterpret_cast<OLE_HANDLE>(m_window.window()))); + EXPECT_HRESULT_SUCCEEDED(m_webView->initWithFrame(m_window.clientRect(), 0, 0)); + + COMPtr<IWebViewPrivate> viewPrivate(Query, m_webView); + ASSERT_NOT_NULL(viewPrivate); + EXPECT_HRESULT_SUCCEEDED(viewPrivate->viewWindow(reinterpret_cast<OLE_HANDLE*>(&m_viewWindow))); + EXPECT_TRUE(::IsWindow(m_viewWindow)); +} + +void WebViewDestruction::runMessagePump(DWORD timeoutMilliseconds) +{ + // FIXME: We should move this functionality to PlatformUtilities at some point. + + DWORD startTickCount = ::GetTickCount(); + MSG msg; + BOOL result; + while ((result = ::PeekMessageW(&msg, 0, 0, 0, PM_REMOVE)) && ::GetTickCount() - startTickCount <= timeoutMilliseconds) { + if (result == -1) + break; + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } +} + +void WebViewDestruction::TearDown() +{ + // Allow window messages to be processed, because in some cases that would trigger a crash (e.g., <http://webkit.org/b/32827>). + runMessagePump(50); + + // We haven't crashed. Release the WebView and ensure that its view window has been destroyed and the WebView doesn't leak. + int currentWebViewCount = webViewCount(); + EXPECT_GT(currentWebViewCount, 0); + + m_webView = 0; + + EXPECT_EQ(webViewCount(), currentWebViewCount - 1); +} + +void WebViewDestructionWithHostWindow::TearDown() +{ + WebViewDestruction::TearDown(); + + EXPECT_FALSE(::IsWindow(m_viewWindow)); +} + +// Tests that releasing a WebView without calling IWebView::initWithFrame works. +TEST_F(WebViewDestruction, NoInitWithFrame) +{ +} + +TEST_F(WebViewDestruction, CloseWithoutInitWithFrame) +{ + EXPECT_HRESULT_SUCCEEDED(m_webView->close()); +} + +// Tests that calling IWebView::close without calling DestroyWindow, then releasing a WebView doesn't crash. <http://webkit.org/b/32827> +TEST_F(WebViewDestructionWithHostWindow, CloseWithoutDestroyViewWindow) +{ + EXPECT_HRESULT_SUCCEEDED(m_webView->close()); +} + +TEST_F(WebViewDestructionWithHostWindow, DestroyViewWindowWithoutClose) +{ + ::DestroyWindow(m_viewWindow); +} + +TEST_F(WebViewDestructionWithHostWindow, CloseThenDestroyViewWindow) +{ + EXPECT_HRESULT_SUCCEEDED(m_webView->close()); + ::DestroyWindow(m_viewWindow); +} + +TEST_F(WebViewDestructionWithHostWindow, DestroyViewWindowThenClose) +{ + ::DestroyWindow(m_viewWindow); + EXPECT_HRESULT_SUCCEEDED(m_webView->close()); +} + +TEST_F(WebViewDestructionWithHostWindow, DestroyHostWindow) +{ + ::DestroyWindow(m_window.window()); +} + +TEST_F(WebViewDestructionWithHostWindow, DestroyHostWindowThenClose) +{ + ::DestroyWindow(m_window.window()); + EXPECT_HRESULT_SUCCEEDED(m_webView->close()); +} + +TEST_F(WebViewDestructionWithHostWindow, CloseThenDestroyHostWindow) +{ + EXPECT_HRESULT_SUCCEEDED(m_webView->close()); + ::DestroyWindow(m_window.window()); +} + +} // namespace WebKitAPITest diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/18-characters.html b/Tools/TestWebKitAPI/Tests/WebKit2/18-characters.html new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/18-characters.html diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/AboutBlankLoad.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/AboutBlankLoad.cpp new file mode 100644 index 000000000..ff36a0b18 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/AboutBlankLoad.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" + +namespace TestWebKitAPI { + +static bool done; + +static void decidePolicyForResponse(WKPageRef, WKFrameRef, WKURLResponseRef response, WKURLRequestRef, WKFramePolicyListenerRef listener, WKTypeRef, const void*) +{ + EXPECT_WK_STREQ("text/html", Util::MIMETypeForWKURLResponse(response)); + + WKFramePolicyListenerUse(listener); + done = true; +} + +TEST(WebKit2, AboutBlankLoad) +{ + WKRetainPtr<WKContextRef> context = adoptWK(WKContextCreate()); + PlatformWebView webView(context.get()); + + WKPagePolicyClient policyClient; + memset(&policyClient, 0, sizeof(policyClient)); + + policyClient.decidePolicyForResponse = decidePolicyForResponse; + WKPageSetPagePolicyClient(webView.page(), &policyClient); + + WKPageLoadURL(webView.page(), adoptWK(WKURLCreateWithUTF8CString("about:blank")).get()); + + Util::run(&done); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/CanHandleRequest.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/CanHandleRequest.cpp new file mode 100644 index 000000000..e3e5d0cc6 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/CanHandleRequest.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include <WebKit2/WKContextPrivate.h> + +namespace TestWebKitAPI { + +static bool didReceiveMessage; +static bool canHandleRequest; + +static void didReceiveMessageFromInjectedBundle(WKContextRef, WKStringRef messageName, WKTypeRef body, const void*) +{ + didReceiveMessage = true; + + EXPECT_WK_STREQ("DidCheckCanHandleRequest", messageName); + EXPECT_EQ(WKBooleanGetTypeID(), WKGetTypeID(body)); + + canHandleRequest = WKBooleanGetValue(static_cast<WKBooleanRef>(body)); +} + +static void setInjectedBundleClient(WKContextRef context) +{ + WKContextInjectedBundleClient injectedBundleClient; + memset(&injectedBundleClient, 0, sizeof(injectedBundleClient)); + injectedBundleClient.didReceiveMessageFromInjectedBundle = didReceiveMessageFromInjectedBundle; + + WKContextSetInjectedBundleClient(context, &injectedBundleClient); +} + +TEST(WebKit2, CanHandleRequest) +{ + WKRetainPtr<WKContextRef> context = adoptWK(Util::createContextForInjectedBundleTest("CanHandleRequestTest")); + setInjectedBundleClient(context.get()); + + WKContextRegisterURLSchemeAsEmptyDocument(context.get(), Util::toWK("emptyscheme").get()); + + PlatformWebView webView(context.get()); + + WKPageLoadURL(webView.page(), adoptWK(Util::createURLForResource("simple", "html")).get()); + + WKContextPostMessageToInjectedBundle(context.get(), Util::toWK("CheckCanHandleRequest").get(), 0); + Util::run(&didReceiveMessage); + EXPECT_TRUE(canHandleRequest); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/CanHandleRequest_Bundle.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/CanHandleRequest_Bundle.cpp new file mode 100644 index 000000000..5f66b537a --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/CanHandleRequest_Bundle.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "InjectedBundleTest.h" + +#include "PlatformUtilities.h" +#include <WebKit2/WKBundlePage.h> + +namespace TestWebKitAPI { + +class CanHandleRequestTest : public InjectedBundleTest { +public: + CanHandleRequestTest(const std::string& identifier); + +private: + virtual void didReceiveMessage(WKBundleRef, WKStringRef messageName, WKTypeRef messageBody); +}; + +static InjectedBundleTest::Register<CanHandleRequestTest> registrar("CanHandleRequestTest"); + +CanHandleRequestTest::CanHandleRequestTest(const std::string& identifier) + : InjectedBundleTest(identifier) +{ +} + +static bool canHandleURL(const char* url) +{ + return WKBundlePageCanHandleRequest(adoptWK(WKURLRequestCreateWithWKURL(adoptWK(WKURLCreateWithUTF8CString(url)).get())).get()); +} + +static bool runTest() +{ + return canHandleURL("about:blank") && canHandleURL("emptyscheme://") && !canHandleURL("notascheme://"); +} + +void CanHandleRequestTest::didReceiveMessage(WKBundleRef bundle, WKStringRef messageName, WKTypeRef) +{ + if (!WKStringIsEqualToUTF8CString(messageName, "CheckCanHandleRequest")) + return; + + WKBundlePostMessage(bundle, Util::toWK("DidCheckCanHandleRequest").get(), adoptWK(WKBooleanCreate(runTest())).get()); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/CookieManager.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/CookieManager.cpp new file mode 100644 index 000000000..df5fb2eb0 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/CookieManager.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include <WebKit2/WKCookieManager.h> +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool testDone; +// Make sure that the policy on the machine running the test is not changed after running the test. +static WKHTTPCookieAcceptPolicy userPolicy; +static WKHTTPCookieAcceptPolicy testPolicy; +static WKRetainPtr<WKContextRef> wkContext; + +static void didGetTestHTTPCookieAcceptPolicy(WKHTTPCookieAcceptPolicy policy, WKErrorRef, void* context) +{ + EXPECT_EQ(reinterpret_cast<void*>(0x1234578), context); + EXPECT_EQ(testPolicy, policy); + + WKCookieManagerRef cookieManager = WKContextGetCookieManager(wkContext.get()); + WKCookieManagerSetHTTPCookieAcceptPolicy(cookieManager, userPolicy); + + testDone = true; +} + +static void didGetUserHTTPCookieAcceptPolicy(WKHTTPCookieAcceptPolicy policy, WKErrorRef, void* context) +{ + EXPECT_EQ(reinterpret_cast<void*>(0x1234578), context); + + userPolicy = policy; + + // Make sure to choose a policy different from the policy the user currently has set. + testPolicy = (userPolicy + 1) % 3; + WKCookieManagerRef cookieManager = WKContextGetCookieManager(wkContext.get()); + WKCookieManagerSetHTTPCookieAcceptPolicy(cookieManager, testPolicy); + WKCookieManagerGetHTTPCookieAcceptPolicy(cookieManager, reinterpret_cast<void*>(0x1234578), didGetTestHTTPCookieAcceptPolicy); +} + +static void didFinishLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef, const void*) +{ + WKCookieManagerRef cookieManager = WKContextGetCookieManager(wkContext.get()); + WKCookieManagerGetHTTPCookieAcceptPolicy(cookieManager, reinterpret_cast<void*>(0x1234578), didGetUserHTTPCookieAcceptPolicy); +} + +TEST(WebKit2, CookieManager) +{ + wkContext.adopt(WKContextCreate()); + PlatformWebView webView(wkContext.get()); + + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + + loaderClient.version = 0; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + WKPageSetPageLoaderClient(webView.page(), &loaderClient); + + WKPageLoadURL(webView.page(), adoptWK(WKURLCreateWithUTF8CString("about:blank")).get()); + + Util::run(&testDone); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/DocumentStartUserScriptAlertCrash.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/DocumentStartUserScriptAlertCrash.cpp new file mode 100644 index 000000000..7559da28d --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/DocumentStartUserScriptAlertCrash.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include "Test.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool done; + +static void runJavaScriptAlert(WKPageRef page, WKStringRef alertText, WKFrameRef frame, const void* clientInfo) +{ + ASSERT_NOT_NULL(frame); + + EXPECT_EQ(page, WKFrameGetPage(frame)); + EXPECT_WK_STREQ("an alert", alertText); + + done = true; +} + +TEST(WebKit2, DocumentStartUserScriptAlertCrashTest) +{ + WKRetainPtr<WKPageGroupRef> pageGroup(AdoptWK, WKPageGroupCreateWithIdentifier(WKStringCreateWithUTF8CString("DocumentStartUserScriptAlertCrashTestPageGroup"))); + + WKRetainPtr<WKContextRef> context(AdoptWK, Util::createContextForInjectedBundleTest("DocumentStartUserScriptAlertCrashTest", pageGroup.get())); + PlatformWebView webView(context.get(), pageGroup.get()); + + WKPageUIClient uiClient; + memset(&uiClient, 0, sizeof(uiClient)); + uiClient.version = 0; + uiClient.clientInfo = 0; + uiClient.runJavaScriptAlert = runJavaScriptAlert; + WKPageSetPageUIClient(webView.page(), &uiClient); + + WKRetainPtr<WKURLRef> url(AdoptWK, Util::createURLForResource("simple", "html")); + WKPageLoadURL(webView.page(), url.get()); + + Util::run(&done); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/DocumentStartUserScriptAlertCrash_Bundle.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/DocumentStartUserScriptAlertCrash_Bundle.cpp new file mode 100644 index 000000000..3aa290981 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/DocumentStartUserScriptAlertCrash_Bundle.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "InjectedBundleTest.h" +#include <WebKit2/WKBundlePageGroup.h> +#include <WebKit2/WKBundlePrivate.h> +#include <WebKit2/WKBundleScriptWorld.h> +#include <WebKit2/WKRetainPtr.h> +#include <assert.h> + +namespace TestWebKitAPI { + +class DocumentStartUserScriptAlertCrashTest : public InjectedBundleTest { +public: + DocumentStartUserScriptAlertCrashTest(const std::string& identifier) + : InjectedBundleTest(identifier) + { + } + + virtual void initialize(WKBundleRef bundle, WKTypeRef userData) + { + assert(WKGetTypeID(userData) == WKBundlePageGroupGetTypeID()); + WKBundlePageGroupRef pageGroup = static_cast<WKBundlePageGroupRef>(userData); + + WKRetainPtr<WKStringRef> source(AdoptWK, WKStringCreateWithUTF8CString("alert('an alert');")); + WKBundleAddUserScript(bundle, pageGroup, WKBundleScriptWorldNormalWorld(), source.get(), 0, 0, 0, kWKInjectAtDocumentStart, kWKInjectInAllFrames); + } + +private: + WKBundlePageGroupRef m_pageGroup; +}; + +static InjectedBundleTest::Register<DocumentStartUserScriptAlertCrashTest> registrar("DocumentStartUserScriptAlertCrashTest"); + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/DownloadDecideDestinationCrash.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/DownloadDecideDestinationCrash.cpp new file mode 100644 index 000000000..f360646dd --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/DownloadDecideDestinationCrash.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include <WebKit2/WKDownload.h> + +namespace TestWebKitAPI { + +static bool didDecideDestination; + +static void decidePolicyForNavigationAction(WKPageRef, WKFrameRef, WKFrameNavigationType, WKEventModifiers, WKEventMouseButton, WKURLRequestRef, WKFramePolicyListenerRef listener, WKTypeRef, const void*) +{ + WKFramePolicyListenerDownload(listener); +} + +static WKStringRef decideDestinationWithSuggestedFilename(WKContextRef, WKDownloadRef download, WKStringRef, bool*, const void*) +{ + didDecideDestination = true; + WKDownloadCancel(download); + return Util::toWK("does not matter").leakRef(); +} + +static void setContextDownloadClient(WKContextRef context) +{ + WKContextDownloadClient client; + memset(&client, 0, sizeof(client)); + client.decideDestinationWithSuggestedFilename = decideDestinationWithSuggestedFilename; + + WKContextSetDownloadClient(context, &client); +} + +static void setPagePolicyClient(WKPageRef page) +{ + WKPagePolicyClient policyClient; + memset(&policyClient, 0, sizeof(policyClient)); + policyClient.decidePolicyForNavigationAction = decidePolicyForNavigationAction; + + WKPageSetPagePolicyClient(page, &policyClient); +} + +TEST(WebKit2, DownloadDecideDestinationCrash) +{ + WKRetainPtr<WKContextRef> context = adoptWK(WKContextCreate()); + setContextDownloadClient(context.get()); + + PlatformWebView webView(context.get()); + setPagePolicyClient(webView.page()); + + // The length of this filename was specially chosen to trigger the crash conditions in + // <http://webkit.org/b/61142>. Specifically, it causes ArgumentDecoder::m_bufferPos and m_bufferEnd + // to be equal after the DecideDestinationWithSuggestedFilename message has been handled. + WKPageLoadURL(webView.page(), adoptWK(Util::createURLForResource("18-characters", "html")).get()); + + Util::run(&didDecideDestination); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/EvaluateJavaScript.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/EvaluateJavaScript.cpp new file mode 100644 index 000000000..99b7ff7f1 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/EvaluateJavaScript.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include "Test.h" +#include <JavaScriptCore/JavaScriptCore.h> +#include <WebKit2/WKRetainPtr.h> +#include <WebKit2/WKSerializedScriptValue.h> + +namespace TestWebKitAPI { + +static bool testDone; + +static void didRunJavaScript(WKSerializedScriptValueRef resultSerializedScriptValue, WKErrorRef error, void* context) +{ + EXPECT_EQ(reinterpret_cast<void*>(0x1234578), context); + EXPECT_NULL(resultSerializedScriptValue); + + // FIXME: We should also check the error, but right now it's always null. + // Assert that it's null so we can revisit when this changes. + EXPECT_NULL(error); + + testDone = true; +} + +TEST(WebKit2, EvaluateJavaScriptThatThrowsAnException) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + PlatformWebView webView(context.get()); + + WKRetainPtr<WKStringRef> javaScriptString(AdoptWK, WKStringCreateWithUTF8CString("throw 'Hello'")); + WKPageRunJavaScriptInMainFrame(webView.page(), javaScriptString.get(), reinterpret_cast<void*>(0x1234578), didRunJavaScript); + + Util::run(&testDone); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/FailedLoad.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/FailedLoad.cpp new file mode 100644 index 000000000..99b1b9744 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/FailedLoad.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include "Test.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +// FIXME: This should also test the that the load state after didFailLoadWithErrorForFrame is kWKFrameLoadStateFinished + +static bool testDone; + +static void didFailProvisionalLoadWithErrorForFrame(WKPageRef page, WKFrameRef frame, WKErrorRef error, WKTypeRef userData, const void* clientInfo) +{ + EXPECT_EQ(static_cast<uint32_t>(kWKFrameLoadStateFinished), WKFrameGetFrameLoadState(frame)); + + WKURLRef url = WKFrameCopyProvisionalURL(frame); + EXPECT_NULL(url); + + testDone = true; +} + +TEST(WebKit2, FailedLoad) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + PlatformWebView webView(context.get()); + + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + + loaderClient.version = 0; + loaderClient.clientInfo = 0; + loaderClient.didFailProvisionalLoadWithErrorForFrame = didFailProvisionalLoadWithErrorForFrame; + WKPageSetPageLoaderClient(webView.page(), &loaderClient); + + WKRetainPtr<WKURLRef> url(AdoptWK, Util::URLForNonExistentResource()); + WKPageLoadURL(webView.page(), url.get()); + + Util::run(&testDone); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/Find.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/Find.cpp new file mode 100644 index 000000000..2717c1355 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/Find.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool didFinishLoad = false; +static bool didCallCountStringMatches = false; + +static void didFinishLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) +{ + didFinishLoad = true; +} + +static void didCountStringMatches(WKPageRef page, WKStringRef string, unsigned numMatches, const void* clientInfo) +{ + EXPECT_WK_STREQ("Hello", string); + EXPECT_EQ(3u, numMatches); + + didCallCountStringMatches = true; +} + +TEST(WebKit2, Find) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + PlatformWebView webView(context.get()); + + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + + loaderClient.version = 0; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + WKPageSetPageLoaderClient(webView.page(), &loaderClient); + + WKPageFindClient findClient; + memset(&findClient, 0, sizeof(findClient)); + + findClient.version = 0; + findClient.didCountStringMatches = didCountStringMatches; + WKPageSetPageFindClient(webView.page(), &findClient); + + WKRetainPtr<WKURLRef> url(AdoptWK, Util::createURLForResource("find", "html")); + WKPageLoadURL(webView.page(), url.get()); + + Util::run(&didFinishLoad); + + WKRetainPtr<WKStringRef> findString(AdoptWK, WKStringCreateWithUTF8CString("Hello")); + WKPageCountStringMatches(webView.page(), findString.get(), true, 100); + + Util::run(&didCallCountStringMatches); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/ForceRepaint.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/ForceRepaint.cpp new file mode 100644 index 000000000..08873f843 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/ForceRepaint.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include "Test.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool test1Done; +static bool test2Done; + +void didForceRepaint(WKErrorRef error, void*) +{ + EXPECT_NULL(error); + test2Done = true; +} + +static void didFinishLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) +{ + test1Done = true; + WKPageForceRepaint(page, 0, didForceRepaint); +} + +TEST(WebKit2, ForceRepaint) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + PlatformWebView webView(context.get()); + + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + + loaderClient.version = 0; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + WKPageSetPageLoaderClient(webView.page(), &loaderClient); + + WKRetainPtr<WKURLRef> url(AdoptWK, Util::createURLForResource("simple-accelerated-compositing", "html")); + WKPageLoadURL(webView.page(), url.get()); + + Util::run(&test1Done); + Util::run(&test2Done); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/FrameMIMETypeHTML.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/FrameMIMETypeHTML.cpp new file mode 100644 index 000000000..734986628 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/FrameMIMETypeHTML.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include "Test.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool testDone; + +static void didStartProvisionalLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) +{ + WKRetainPtr<WKStringRef> wkMIME = adoptWK(WKFrameCopyMIMEType(frame)); + EXPECT_TRUE(WKStringIsEmpty(wkMIME.get())); +} + +static void didCommitLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) +{ + WKRetainPtr<WKStringRef> wkMIME = adoptWK(WKFrameCopyMIMEType(frame)); + EXPECT_WK_STREQ("text/html", wkMIME); +} + +static void didFinishLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) +{ + WKRetainPtr<WKStringRef> wkMIME = adoptWK(WKFrameCopyMIMEType(frame)); + EXPECT_WK_STREQ("text/html", wkMIME); + + testDone = true; +} + +TEST(WebKit2, FrameMIMETypeHTML) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + PlatformWebView webView(context.get()); + + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + + loaderClient.version = 0; + loaderClient.clientInfo = 0; + loaderClient.didStartProvisionalLoadForFrame = didStartProvisionalLoadForFrame; + loaderClient.didCommitLoadForFrame = didCommitLoadForFrame; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + WKPageSetPageLoaderClient(webView.page(), &loaderClient); + + WKRetainPtr<WKURLRef> url(AdoptWK, Util::createURLForResource("simple", "html")); + WKPageLoadURL(webView.page(), url.get()); + + Util::run(&testDone); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/FrameMIMETypePNG.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/FrameMIMETypePNG.cpp new file mode 100644 index 000000000..46f63dae9 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/FrameMIMETypePNG.cpp @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool testDone; + +static void didStartProvisionalLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) +{ + WKRetainPtr<WKStringRef> wkMIME = adoptWK(WKFrameCopyMIMEType(frame)); + EXPECT_TRUE(WKStringIsEmpty(wkMIME.get())); +} + +static void didCommitLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) +{ + WKRetainPtr<WKStringRef> wkMIME = adoptWK(WKFrameCopyMIMEType(frame)); + EXPECT_WK_STREQ("image/png", wkMIME); +} + +static void didFinishLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) +{ + WKRetainPtr<WKStringRef> wkMIME = adoptWK(WKFrameCopyMIMEType(frame)); + EXPECT_WK_STREQ("image/png", wkMIME); + + testDone = true; +} + +TEST(WebKit2, FrameMIMETypePNG) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + PlatformWebView webView(context.get()); + + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + + loaderClient.version = 0; + loaderClient.clientInfo = 0; + loaderClient.didStartProvisionalLoadForFrame = didStartProvisionalLoadForFrame; + loaderClient.didCommitLoadForFrame = didCommitLoadForFrame; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + WKPageSetPageLoaderClient(webView.page(), &loaderClient); + + WKRetainPtr<WKURLRef> url(AdoptWK, Util::createURLForResource("icon", "png")); + WKPageLoadURL(webView.page(), url.get()); + + Util::run(&testDone); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/HitTestResultNodeHandle.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/HitTestResultNodeHandle.cpp new file mode 100644 index 000000000..2100d28c3 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/HitTestResultNodeHandle.cpp @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool done; +static bool messageReceived; +static bool didFinishLoad; + +static void didFinishLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef, const void*) +{ + didFinishLoad = true; +} + +static void didReceiveMessageFromInjectedBundle(WKContextRef context, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo) +{ + messageReceived = true; + if (WKStringIsEqualToUTF8CString(messageName, "HitTestResultNodeHandleTestDoneMessageName")) + done = true; +} + +static void setPageLoaderClient(WKPageRef page) +{ + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + loaderClient.version = 0; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + + WKPageSetPageLoaderClient(page, &loaderClient); +} + +static void setInjectedBundleClient(WKContextRef context) +{ + WKContextInjectedBundleClient injectedBundleClient; + memset(&injectedBundleClient, 0, sizeof(injectedBundleClient)); + injectedBundleClient.version = 0; + injectedBundleClient.clientInfo = 0; + injectedBundleClient.didReceiveMessageFromInjectedBundle = didReceiveMessageFromInjectedBundle; + WKContextSetInjectedBundleClient(context, &injectedBundleClient); +} + +TEST(WebKit2, HitTestResultNodeHandle) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, Util::createContextForInjectedBundleTest("HitTestResultNodeHandleTest")); + + setInjectedBundleClient(context.get()); + + PlatformWebView webView(context.get()); + setPageLoaderClient(webView.page()); + + WKPageLoadURL(webView.page(), adoptWK(Util::createURLForResource("simple", "html")).get()); + Util::run(&didFinishLoad); + didFinishLoad = false; + + webView.simulateRightClick(10, 10); + Util::run(&done); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/HitTestResultNodeHandle_Bundle.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/HitTestResultNodeHandle_Bundle.cpp new file mode 100644 index 000000000..882909e81 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/HitTestResultNodeHandle_Bundle.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "InjectedBundleTest.h" +#include "InjectedBundleController.h" +#include "PlatformUtilities.h" +#include <WebKit2/WKBundlePage.h> +#include <WebKit2/WKBundleHitTestResult.h> +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +class HitTestResultNodeHandleTest : public InjectedBundleTest { +public: + HitTestResultNodeHandleTest(const std::string& identifier) + : InjectedBundleTest(identifier) + { + } + + static void getContextMenuFromDefaultMenu(WKBundlePageRef page, WKBundleHitTestResultRef hitTestResult, WKArrayRef defaultMenu, WKArrayRef* newMenu, WKTypeRef* userData, const void* clientInfo) + { + WKRetainPtr<WKBundleNodeHandleRef> nodeHandle(AdoptWK, WKBundleHitTestResultCopyNodeHandle(hitTestResult)); + if (!nodeHandle) + return; + + WKBundlePostMessage(InjectedBundleController::shared().bundle(), Util::toWK("HitTestResultNodeHandleTestDoneMessageName").get(), Util::toWK("HitTestResultNodeHandleTestDoneMessageBody").get()); + } + + virtual void didCreatePage(WKBundleRef bundle, WKBundlePageRef page) + { + WKBundlePageContextMenuClient contextMenuClient; + memset(&contextMenuClient, 0, sizeof(contextMenuClient)); + contextMenuClient.getContextMenuFromDefaultMenu = getContextMenuFromDefaultMenu; + + WKBundlePageSetContextMenuClient(page, &contextMenuClient); + } +}; + +static InjectedBundleTest::Register<HitTestResultNodeHandleTest> registrar("HitTestResultNodeHandleTest"); + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/InjectedBundleBasic.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/InjectedBundleBasic.cpp new file mode 100644 index 000000000..40ca269df --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/InjectedBundleBasic.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool done; +static bool loadDone; +static bool messageReceived; + +void didReceiveMessageFromInjectedBundle(WKContextRef context, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo) +{ + messageReceived = true; + if (loadDone) + done = true; +} + +static void didFinishLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) +{ + loadDone = true; + if (messageReceived) + done = true; +} + +TEST(WebKit2, InjectedBundleBasic) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, Util::createContextForInjectedBundleTest("InjectedBundleBasicTest")); + + WKContextInjectedBundleClient injectedBundleClient; + memset(&injectedBundleClient, 0, sizeof(injectedBundleClient)); + injectedBundleClient.version = 0; + injectedBundleClient.clientInfo = 0; + injectedBundleClient.didReceiveMessageFromInjectedBundle = didReceiveMessageFromInjectedBundle; + WKContextSetInjectedBundleClient(context.get(), &injectedBundleClient); + + PlatformWebView webView(context.get()); + + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + loaderClient.version = 0; + loaderClient.clientInfo = 0; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + WKPageSetPageLoaderClient(webView.page(), &loaderClient); + + WKRetainPtr<WKURLRef> url(AdoptWK, Util::createURLForResource("simple", "html")); + WKPageLoadURL(webView.page(), url.get()); + + Util::run(&done); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/InjectedBundleBasic_Bundle.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/InjectedBundleBasic_Bundle.cpp new file mode 100644 index 000000000..6a597be41 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/InjectedBundleBasic_Bundle.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "InjectedBundleTest.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +class InjectedBundleBasicTest : public InjectedBundleTest { +public: + InjectedBundleBasicTest(const std::string& identifier) + : InjectedBundleTest(identifier) + { + } + + virtual void didCreatePage(WKBundleRef bundle, WKBundlePageRef page) + { + WKRetainPtr<WKStringRef> doneMessageName = adoptWK(WKStringCreateWithUTF8CString("DoneMessageName")); + WKRetainPtr<WKStringRef> doneMessageBody = adoptWK(WKStringCreateWithUTF8CString("DoneMessageBody")); + WKBundlePostMessage(bundle, doneMessageName.get(), doneMessageBody.get()); + } +}; + +static InjectedBundleTest::Register<InjectedBundleBasicTest> registrar("InjectedBundleBasicTest"); + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/LoadAlternateHTMLStringWithNonDirectoryURL.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/LoadAlternateHTMLStringWithNonDirectoryURL.cpp new file mode 100644 index 000000000..78787414d --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/LoadAlternateHTMLStringWithNonDirectoryURL.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JavaScriptTest.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" + +#include <WebKit2/WKContext.h> +#include <WebKit2/WKPage.h> +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool didFinishLoad = false; + +static void didFinishLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) +{ + didFinishLoad = true; +} + +TEST(WebKit2, LoadAlternateHTMLStringWithNonDirectoryURL) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + PlatformWebView webView(context.get()); + + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + + loaderClient.version = 0; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + WKPageSetPageLoaderClient(webView.page(), &loaderClient); + + WKRetainPtr<WKURLRef> fileURL(AdoptWK, Util::createURLForResource("simple", "html")); + WKRetainPtr<WKStringRef> alternateHTMLString(AdoptWK, WKStringCreateWithUTF8CString("<html><body><img src='icon.png'></body></html>")); + + // Call WKPageLoadAlternateHTMLString() with fileURL which does not point to a directory + WKPageLoadAlternateHTMLString(webView.page(), alternateHTMLString.get(), fileURL.get(), fileURL.get()); + + // If we can finish loading the html without resulting in an invalid message being sent from the WebProcess, this test passes. + Util::run(&didFinishLoad); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/LoadCanceledNoServerRedirectCallback.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/LoadCanceledNoServerRedirectCallback.cpp new file mode 100644 index 000000000..7dbd063bc --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/LoadCanceledNoServerRedirectCallback.cpp @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JavaScriptTest.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" + +#include <WebKit2/WKContext.h> +#include <WebKit2/WKFrame.h> +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool loadedMainFrame; +static bool loadedIFrame; +static bool loadedAllFrames; + +static bool performedServerRedirect; + +static void didFinishLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef, const void*) +{ + if (WKFrameIsMainFrame(frame)) + loadedMainFrame = true; + else + loadedIFrame = true; + + loadedAllFrames = loadedMainFrame && loadedIFrame; +} + +static void didPerformServerRedirect(WKContextRef context, WKPageRef page, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void *clientInfo) +{ + performedServerRedirect = true; +} + +TEST(WebKit2, LoadCanceledNoServerRedirectCallback) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, Util::createContextForInjectedBundleTest("LoadCanceledNoServerRedirectCallbackTest")); + + WKContextInjectedBundleClient injectedBundleClient; + memset(&injectedBundleClient, 0, sizeof(injectedBundleClient)); + injectedBundleClient.version = 0; + injectedBundleClient.clientInfo = 0; + WKContextSetInjectedBundleClient(context.get(), &injectedBundleClient); + + PlatformWebView webView(context.get()); + + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + + loaderClient.version = 0; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + WKPageSetPageLoaderClient(webView.page(), &loaderClient); + + WKContextHistoryClient historyClient; + memset(&historyClient, 0, sizeof(historyClient)); + + historyClient.version = 0; + historyClient.didPerformServerRedirect = didPerformServerRedirect; + WKContextSetHistoryClient(context.get(), &historyClient); + + WKRetainPtr<WKURLRef> url(AdoptWK, Util::createURLForResource("simple-iframe", "html")); + WKPageLoadURL(webView.page(), url.get()); + Util::run(&loadedAllFrames); + + // We shouldn't have performed a server redirect when the iframe load was cancelled. + EXPECT_FALSE(performedServerRedirect); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/LoadCanceledNoServerRedirectCallback_Bundle.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/LoadCanceledNoServerRedirectCallback_Bundle.cpp new file mode 100644 index 000000000..0792c3f8a --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/LoadCanceledNoServerRedirectCallback_Bundle.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "InjectedBundleTest.h" +#include "PlatformUtilities.h" +#include "Test.h" + +#include <WebKit2/WKBundlePage.h> +#include <WebKit2/WKBundleFrame.h> +#include <WebKit2/WKRetainPtr.h> + +#include <wtf/Assertions.h> + +namespace TestWebKitAPI { + +class LoadCanceledNoServerRedirectCallbackTest : public InjectedBundleTest { +public: + LoadCanceledNoServerRedirectCallbackTest(const std::string& identifier) + : InjectedBundleTest(identifier) + { + } + + static WKURLRequestRef willSendRequestForFrame(WKBundlePageRef, WKBundleFrameRef frame, uint64_t resourceIdentifier, WKURLRequestRef request, WKURLResponseRef redirectResponse, const void *clientInfo) + { + // Allow the loading of the main resource, but don't allow the loading of an iframe, return null from willSendRequest. + if (WKBundleFrameIsMainFrame(frame)) { + WKRetainPtr<WKURLRequestRef> newRequest = request; + return newRequest.leakRef(); + } + + return 0; + } + + virtual void didCreatePage(WKBundleRef bundle, WKBundlePageRef page) + { + WKBundlePageResourceLoadClient resourceLoadClient; + memset(&resourceLoadClient, 0, sizeof(resourceLoadClient)); + + resourceLoadClient.version = 0; + resourceLoadClient.willSendRequestForFrame = willSendRequestForFrame; + + WKBundlePageSetResourceLoadClient(page, &resourceLoadClient); + + } +}; + +static InjectedBundleTest::Register<LoadCanceledNoServerRedirectCallbackTest> registrar("LoadCanceledNoServerRedirectCallbackTest"); + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/MouseMoveAfterCrash.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/MouseMoveAfterCrash.cpp new file mode 100644 index 000000000..c5e851459 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/MouseMoveAfterCrash.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JavaScriptTest.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" + +namespace TestWebKitAPI { + +static bool didFinishLoad; + +static void didFinishLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef, const void*) +{ + didFinishLoad = true; +} + +static void processDidCrash(WKPageRef page, const void*) +{ + WKPageReload(page); +} + +static void setPageLoaderClient(WKPageRef page) +{ + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + loaderClient.version = 0; + loaderClient.clientInfo = 0; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + loaderClient.processDidCrash = processDidCrash; + + WKPageSetPageLoaderClient(page, &loaderClient); +} + +TEST(WebKit2, MouseMoveAfterCrash) +{ + WKRetainPtr<WKContextRef> context = adoptWK(Util::createContextForInjectedBundleTest("MouseMoveAfterCrashTest")); + + PlatformWebView webView(context.get()); + setPageLoaderClient(webView.page()); + + WKRetainPtr<WKURLRef> url(AdoptWK, Util::createURLForResource("mouse-move-listener", "html")); + WKPageLoadURL(webView.page(), url.get()); + Util::run(&didFinishLoad); + + didFinishLoad = false; + + WKContextPostMessageToInjectedBundle(context.get(), Util::toWK("Pause").get(), 0); + + webView.simulateSpacebarKeyPress(); + + // Move the mouse once we are hung. + webView.simulateMouseMove(10, 10); + webView.simulateMouseMove(20, 20); + + // After moving the mouse (while the web process was hung on the Pause message), kill the web process. It is restarted in + // processDidCrash by reloading the page. + WKPageTerminate(webView.page()); + + // Wait until we load the page a second time (via reloading the page in processDidCrash). + Util::run(&didFinishLoad); + + EXPECT_JS_FALSE(webView.page(), "didMoveMouse()"); + + // Once the page has reloaded, try moving the mouse to verify that we get mouse move events. + webView.simulateMouseMove(10, 10); + webView.simulateMouseMove(20, 20); + + EXPECT_JS_TRUE(webView.page(), "didMoveMouse()"); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/MouseMoveAfterCrash_Bundle.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/MouseMoveAfterCrash_Bundle.cpp new file mode 100644 index 000000000..a07562093 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/MouseMoveAfterCrash_Bundle.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "InjectedBundleTest.h" + +#include "PlatformUtilities.h" + +namespace TestWebKitAPI { + +class MouseMoveAfterCrashTest : public InjectedBundleTest { +public: + MouseMoveAfterCrashTest(const std::string& identifier); + +private: + virtual void didReceiveMessage(WKBundleRef, WKStringRef messageName, WKTypeRef messageBody); +}; + +static InjectedBundleTest::Register<MouseMoveAfterCrashTest> registrar("MouseMoveAfterCrashTest"); + +MouseMoveAfterCrashTest::MouseMoveAfterCrashTest(const std::string& identifier) + : InjectedBundleTest(identifier) +{ +} + +void MouseMoveAfterCrashTest::didReceiveMessage(WKBundleRef bundle, WKStringRef messageName, WKTypeRef) +{ + if (!WKStringIsEqualToUTF8CString(messageName, "Pause")) + return; + + Util::sleep(30); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/PageLoadBasic.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/PageLoadBasic.cpp new file mode 100644 index 000000000..0191b6593 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/PageLoadBasic.cpp @@ -0,0 +1,142 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include "Test.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool test1Done; + +struct State { + State() + : didDecidePolicyForNavigationAction(false) + , didStartProvisionalLoadForFrame(false) + , didCommitLoadForFrame(false) + { + } + + bool didDecidePolicyForNavigationAction; + bool didStartProvisionalLoadForFrame; + bool didCommitLoadForFrame; +}; + +static void didStartProvisionalLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) +{ + State* state = reinterpret_cast<State*>(const_cast<void*>(clientInfo)); + EXPECT_TRUE(state->didDecidePolicyForNavigationAction); + EXPECT_FALSE(state->didCommitLoadForFrame); + + // The commited URL should be null. + EXPECT_NULL(WKFrameCopyURL(frame)); + + EXPECT_FALSE(state->didStartProvisionalLoadForFrame); + + state->didStartProvisionalLoadForFrame = true; +} + +static void didCommitLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) +{ + State* state = reinterpret_cast<State*>(const_cast<void*>(clientInfo)); + EXPECT_TRUE(state->didDecidePolicyForNavigationAction); + EXPECT_TRUE(state->didStartProvisionalLoadForFrame); + + // The provisional URL should be null. + EXPECT_NULL(WKFrameCopyProvisionalURL(frame)); + + state->didCommitLoadForFrame = true; +} + +static void didFinishLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) +{ + State* state = reinterpret_cast<State*>(const_cast<void*>(clientInfo)); + EXPECT_TRUE(state->didDecidePolicyForNavigationAction); + EXPECT_TRUE(state->didStartProvisionalLoadForFrame); + EXPECT_TRUE(state->didCommitLoadForFrame); + + // The provisional URL should be null. + EXPECT_NULL(WKFrameCopyProvisionalURL(frame)); + + test1Done = true; +} + +static void decidePolicyForNavigationAction(WKPageRef page, WKFrameRef frame, WKFrameNavigationType navigationType, WKEventModifiers modifiers, WKEventMouseButton mouseButton, WKURLRequestRef request, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo) +{ + State* state = reinterpret_cast<State*>(const_cast<void*>(clientInfo)); + EXPECT_FALSE(state->didStartProvisionalLoadForFrame); + EXPECT_FALSE(state->didCommitLoadForFrame); + + state->didDecidePolicyForNavigationAction = true; + + WKFramePolicyListenerUse(listener); +} + +static void decidePolicyForNewWindowAction(WKPageRef page, WKFrameRef frame, WKFrameNavigationType navigationType, WKEventModifiers modifiers, WKEventMouseButton mouseButton, WKURLRequestRef request, WKStringRef frameName, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo) +{ + WKFramePolicyListenerUse(listener); +} + +static void decidePolicyForResponse(WKPageRef page, WKFrameRef frame, WKURLResponseRef response, WKURLRequestRef request, WKFramePolicyListenerRef listener, WKTypeRef userData, const void* clientInfo) +{ + WKFramePolicyListenerUse(listener); +} + +TEST(WebKit2, PageLoadBasic) +{ + State state; + + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + PlatformWebView webView(context.get()); + + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + + loaderClient.version = 0; + loaderClient.clientInfo = &state; + loaderClient.didStartProvisionalLoadForFrame = didStartProvisionalLoadForFrame; + loaderClient.didCommitLoadForFrame = didCommitLoadForFrame; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + WKPageSetPageLoaderClient(webView.page(), &loaderClient); + + WKPagePolicyClient policyClient; + memset(&policyClient, 0, sizeof(policyClient)); + + policyClient.version = 0; + policyClient.clientInfo = &state; + policyClient.decidePolicyForNavigationAction = decidePolicyForNavigationAction; + policyClient.decidePolicyForNewWindowAction = decidePolicyForNewWindowAction; + policyClient.decidePolicyForResponse = decidePolicyForResponse; + WKPageSetPagePolicyClient(webView.page(), &policyClient); + + WKRetainPtr<WKURLRef> url(AdoptWK, Util::createURLForResource("simple", "html")); + WKPageLoadURL(webView.page(), url.get()); + + Util::run(&test1Done); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/PageLoadDidChangeLocationWithinPageForFrame.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/PageLoadDidChangeLocationWithinPageForFrame.cpp new file mode 100644 index 000000000..86fbe5ed6 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/PageLoadDidChangeLocationWithinPageForFrame.cpp @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static void nullJavaScriptCallback(WKSerializedScriptValueRef, WKErrorRef error, void*) +{ +} + +static bool didFinishLoad; +static void didFinishLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef, const void*) +{ + didFinishLoad = true; +} + +static bool didPopStateWithinPage; +static bool didChangeLocationWithinPage; +static void didSameDocumentNavigationForFrame(WKPageRef, WKFrameRef, WKSameDocumentNavigationType type, WKTypeRef, const void*) +{ + if (!didPopStateWithinPage) { + EXPECT_EQ(static_cast<uint32_t>(kWKSameDocumentNavigationSessionStatePop), type); + EXPECT_FALSE(didChangeLocationWithinPage); + didPopStateWithinPage = true; + return; + } + + EXPECT_EQ(static_cast<uint32_t>(kWKSameDocumentNavigationAnchorNavigation), type); + didChangeLocationWithinPage = true; +} + +TEST(WebKit2, PageLoadDidChangeLocationWithinPageForFrame) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + PlatformWebView webView(context.get()); + + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + loaderClient.didSameDocumentNavigationForFrame = didSameDocumentNavigationForFrame; + WKPageSetPageLoaderClient(webView.page(), &loaderClient); + + WKRetainPtr<WKURLRef> url(AdoptWK, Util::createURLForResource("file-with-anchor", "html")); + WKPageLoadURL(webView.page(), url.get()); + Util::run(&didFinishLoad); + + WKRetainPtr<WKURLRef> initialURL = adoptWK(WKFrameCopyURL(WKPageGetMainFrame(webView.page()))); + + WKPageRunJavaScriptInMainFrame(webView.page(), Util::toWK("clickLink()").get(), 0, nullJavaScriptCallback); + Util::run(&didChangeLocationWithinPage); + + WKRetainPtr<WKURLRef> urlAfterAnchorClick = adoptWK(WKFrameCopyURL(WKPageGetMainFrame(webView.page()))); + + EXPECT_FALSE(WKURLIsEqual(initialURL.get(), urlAfterAnchorClick.get())); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/PreventEmptyUserAgent.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/PreventEmptyUserAgent.cpp new file mode 100644 index 000000000..4c522780d --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/PreventEmptyUserAgent.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include "Test.h" +#include <JavaScriptCore/JavaScriptCore.h> +#include <WebKit2/WKRetainPtr.h> +#include <WebKit2/WKSerializedScriptValue.h> + +namespace TestWebKitAPI { + +static bool testDone; + +static void didRunJavaScript(WKSerializedScriptValueRef resultSerializedScriptValue, WKErrorRef error, void* context) +{ + EXPECT_EQ(reinterpret_cast<void*>(0x1234578), context); + EXPECT_NOT_NULL(resultSerializedScriptValue); + + JSGlobalContextRef scriptContext = JSGlobalContextCreate(0); + JSValueRef scriptValue = WKSerializedScriptValueDeserialize(resultSerializedScriptValue, scriptContext, 0); + EXPECT_TRUE(JSValueIsString(scriptContext, scriptValue)); + + // Make sure that the result of navigator.userAgent isn't empty, even if we set the custom + // user agent to the empty string. + JSStringRef scriptString = JSValueToStringCopy(scriptContext, scriptValue, 0); + EXPECT_GT(JSStringGetLength(scriptString), 0u); + + JSStringRelease(scriptString); + JSGlobalContextRelease(scriptContext); + + testDone = true; +} + +TEST(WebKit2, PreventEmptyUserAgent) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + PlatformWebView webView(context.get()); + + WKPageSetCustomUserAgent(webView.page(), WKStringCreateWithUTF8CString("")); + WKRetainPtr<WKStringRef> javaScriptString(AdoptWK, WKStringCreateWithUTF8CString("navigator.userAgent")); + WKPageRunJavaScriptInMainFrame(webView.page(), javaScriptString.get(), reinterpret_cast<void*>(0x1234578), didRunJavaScript); + + Util::run(&testDone); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/PrivateBrowsingPushStateNoHistoryCallback.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/PrivateBrowsingPushStateNoHistoryCallback.cpp new file mode 100644 index 000000000..164466b2c --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/PrivateBrowsingPushStateNoHistoryCallback.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include "Test.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool testDone; + +static void didNavigateWithNavigationData(WKContextRef context, WKPageRef page, WKNavigationDataRef navigationData, WKFrameRef frame, const void* clientInfo) +{ + // This should never be called when navigating in Private Browsing. + FAIL(); +} + +static void didSameDocumentNavigationForFrame(WKPageRef page, WKFrameRef frame, WKSameDocumentNavigationType type, WKTypeRef userData, const void *clientInfo) +{ + testDone = true; +} + +TEST(WebKit2, PrivateBrowsingPushStateNoHistoryCallback) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + + WKContextHistoryClient historyClient; + memset(&historyClient, 0, sizeof(historyClient)); + + historyClient.version = 0; + historyClient.clientInfo = 0; + historyClient.didNavigateWithNavigationData = didNavigateWithNavigationData; + WKContextSetHistoryClient(context.get(), &historyClient); + + PlatformWebView webView(context.get()); + + WKPageLoaderClient pageLoaderClient; + memset(&pageLoaderClient, 0, sizeof(pageLoaderClient)); + + pageLoaderClient.version = 0; + pageLoaderClient.clientInfo = 0; + pageLoaderClient.didSameDocumentNavigationForFrame = didSameDocumentNavigationForFrame; + WKPageSetPageLoaderClient(webView.page(), &pageLoaderClient); + + WKRetainPtr<WKPreferencesRef> preferences(AdoptWK, WKPreferencesCreate()); + WKPreferencesSetPrivateBrowsingEnabled(preferences.get(), true); + + WKPageGroupRef pageGroup = WKPageGetPageGroup(webView.page()); + WKPageGroupSetPreferences(pageGroup, preferences.get()); + + WKRetainPtr<WKURLRef> url(AdoptWK, Util::createURLForResource("push-state", "html")); + WKPageLoadURL(webView.page(), url.get()); + + Util::run(&testDone); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/ResponsivenessTimerDoesntFireEarly.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/ResponsivenessTimerDoesntFireEarly.cpp new file mode 100644 index 000000000..10f04c180 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/ResponsivenessTimerDoesntFireEarly.cpp @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" + +namespace TestWebKitAPI { + +static bool didFinishLoad; +static bool didBecomeUnresponsive; +static bool didBrieflyPause; + +static void didReceiveMessageFromInjectedBundle(WKContextRef, WKStringRef messageName, WKTypeRef, const void*) +{ + didBrieflyPause = true; + EXPECT_WK_STREQ("DidBrieflyPause", messageName); +} + +static void didFinishLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef, const void*) +{ + didFinishLoad = true; +} + +static void processDidBecomeUnresponsive(WKPageRef, const void*) +{ + didBecomeUnresponsive = true; +} + +static void setInjectedBundleClient(WKContextRef context) +{ + WKContextInjectedBundleClient injectedBundleClient; + memset(&injectedBundleClient, 0, sizeof(injectedBundleClient)); + injectedBundleClient.version = 0; + injectedBundleClient.clientInfo = 0; + injectedBundleClient.didReceiveMessageFromInjectedBundle = didReceiveMessageFromInjectedBundle; + + WKContextSetInjectedBundleClient(context, &injectedBundleClient); +} + +static void setPageLoaderClient(WKPageRef page) +{ + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + loaderClient.version = 0; + loaderClient.clientInfo = 0; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + loaderClient.processDidBecomeUnresponsive = processDidBecomeUnresponsive; + + WKPageSetPageLoaderClient(page, &loaderClient); +} + +TEST(WebKit2, ResponsivenessTimerDoesntFireEarly) +{ + WKRetainPtr<WKContextRef> context = adoptWK(Util::createContextForInjectedBundleTest("ResponsivenessTimerDoesntFireEarlyTest")); + setInjectedBundleClient(context.get()); + + PlatformWebView webView(context.get()); + setPageLoaderClient(webView.page()); + + WKPageLoadURL(webView.page(), adoptWK(Util::createURLForResource("simple", "html")).get()); + Util::run(&didFinishLoad); + + WKContextPostMessageToInjectedBundle(context.get(), Util::toWK("BrieflyPause").get(), 0); + + // Pressing a key on the keyboard should start the responsiveness timer. Since the web process + // is going to pause before it receives this keypress, it should take a little while to respond + // (but not so long that the responsiveness timer fires). + webView.simulateSpacebarKeyPress(); + + Util::run(&didBrieflyPause); + + EXPECT_FALSE(didBecomeUnresponsive); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/ResponsivenessTimerDoesntFireEarly_Bundle.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/ResponsivenessTimerDoesntFireEarly_Bundle.cpp new file mode 100644 index 000000000..50d664f38 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/ResponsivenessTimerDoesntFireEarly_Bundle.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "InjectedBundleTest.h" + +#include "PlatformUtilities.h" + +namespace TestWebKitAPI { + +class ResponsivenessTimerDoesntFireEarlyTest : public InjectedBundleTest { +public: + ResponsivenessTimerDoesntFireEarlyTest(const std::string& identifier); + +private: + virtual void didReceiveMessage(WKBundleRef, WKStringRef messageName, WKTypeRef messageBody); +}; + +static InjectedBundleTest::Register<ResponsivenessTimerDoesntFireEarlyTest> registrar("ResponsivenessTimerDoesntFireEarlyTest"); + +ResponsivenessTimerDoesntFireEarlyTest::ResponsivenessTimerDoesntFireEarlyTest(const std::string& identifier) + : InjectedBundleTest(identifier) +{ +} + +void ResponsivenessTimerDoesntFireEarlyTest::didReceiveMessage(WKBundleRef bundle, WKStringRef messageName, WKTypeRef) +{ + if (!WKStringIsEqualToUTF8CString(messageName, "BrieflyPause")) + return; + + // The responsiveness timer is a 3-second timer. Pausing for 0.5 seconds should not cause it to fire. + Util::sleep(0.5); + + WKBundlePostMessage(bundle, Util::toWK("DidBrieflyPause").get(), 0); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/RestoreSessionStateContainingFormData.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/RestoreSessionStateContainingFormData.cpp new file mode 100644 index 000000000..f75de124e --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/RestoreSessionStateContainingFormData.cpp @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JavaScriptTest.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include "Test.h" + +namespace TestWebKitAPI { + +static bool didFinishLoad; + +static void didFinishLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef, const void*) +{ + didFinishLoad = true; +} + +static void setPageLoaderClient(WKPageRef page) +{ + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + loaderClient.version = 0; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + + WKPageSetPageLoaderClient(page, &loaderClient); +} + +static WKRetainPtr<WKDataRef> createSessionStateContainingFormData(WKContextRef context) +{ + PlatformWebView webView(context); + setPageLoaderClient(webView.page()); + + WKPageLoadURL(webView.page(), adoptWK(Util::createURLForResource("simple-form", "html")).get()); + Util::run(&didFinishLoad); + didFinishLoad = false; + + EXPECT_JS_EQ(webView.page(), "submitForm()", "undefined"); + Util::run(&didFinishLoad); + didFinishLoad = false; + + return adoptWK(WKPageCopySessionState(webView.page(), 0, 0)); +} + +TEST(WebKit2, RestoreSessionStateContainingFormData) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + + // FIXME: Once <rdar://problem/8708435> is fixed, we can move the creation of this + // PlatformWebView after the call to createSessionStaetContainingFormData. Until then, it must + // remain here to avoid a race condition between the UI and web processes. + PlatformWebView webView(context.get()); + setPageLoaderClient(webView.page()); + + WKRetainPtr<WKDataRef> data = createSessionStateContainingFormData(context.get()); + EXPECT_NOT_NULL(data); + + WKPageRestoreFromSessionState(webView.page(), data.get()); + Util::run(&didFinishLoad); + + EXPECT_TRUE(WKPageCanGoBack(webView.page())); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/SpacebarScrolling.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/SpacebarScrolling.cpp new file mode 100644 index 000000000..f87da5878 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/SpacebarScrolling.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JavaScriptTest.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool didFinishLoad; +static bool didNotHandleKeyDownEvent; + +static void didFinishLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef, const void*) +{ + didFinishLoad = true; +} + +static void didNotHandleKeyEventCallback(WKPageRef, WKNativeEventPtr event, const void*) +{ + if (Util::isKeyDown(event)) + didNotHandleKeyDownEvent = true; +} + +TEST(WebKit2, SpacebarScrolling) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, Util::createContextWithInjectedBundle()); + PlatformWebView webView(context.get()); + + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + + loaderClient.version = 0; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + WKPageSetPageLoaderClient(webView.page(), &loaderClient); + + WKPageUIClient uiClient; + memset(&uiClient, 0, sizeof(uiClient)); + + uiClient.didNotHandleKeyEvent = didNotHandleKeyEventCallback; + WKPageSetPageUIClient(webView.page(), &uiClient); + + WKRetainPtr<WKURLRef> url(AdoptWK, Util::createURLForResource("spacebar-scrolling", "html")); + WKPageLoadURL(webView.page(), url.get()); + Util::run(&didFinishLoad); + + EXPECT_JS_FALSE(webView.page(), "isDocumentScrolled()"); + EXPECT_JS_FALSE(webView.page(), "textFieldContainsSpace()"); + + webView.simulateSpacebarKeyPress(); + + EXPECT_JS_FALSE(webView.page(), "isDocumentScrolled()"); + EXPECT_JS_TRUE(webView.page(), "textFieldContainsSpace()"); + + // On Mac, a key down event represents both a raw key down and a key press. On Windows, a key + // down event only represents a raw key down. We expect the key press to be handled (because it + // inserts text into the text field). But the raw key down should not be handled. +#if PLATFORM(MAC) + EXPECT_FALSE(didNotHandleKeyDownEvent); +#elif PLATFORM(WIN) + EXPECT_TRUE(didNotHandleKeyDownEvent); +#endif + + EXPECT_JS_EQ(webView.page(), "blurTextField()", "undefined"); + + didNotHandleKeyDownEvent = false; + webView.simulateSpacebarKeyPress(); + + EXPECT_JS_TRUE(webView.page(), "isDocumentScrolled()"); + EXPECT_JS_TRUE(webView.page(), "textFieldContainsSpace()"); + +#if PLATFORM(MAC) + EXPECT_FALSE(didNotHandleKeyDownEvent); +#elif PLATFORM(WIN) + EXPECT_TRUE(didNotHandleKeyDownEvent); +#endif +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/WKConnection.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/WKConnection.cpp new file mode 100644 index 000000000..d2782a446 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/WKConnection.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include "Test.h" + +namespace TestWebKitAPI { + +// State for part 1 - setting up the connection. +static bool connectionEstablished; +static WKConnectionRef connectionToBundle; + +// State for part 2 - send/recieving messages. +static bool messageReceived; + +// State for part 3 - tearing down the connection. +static bool connectionTornDown; + + +/* WKContextConnectionClient */ +static void didCreateConnection(WKContextRef context, WKConnectionRef connection, const void* clientInfo) +{ + connectionEstablished = true; + + // Store off the conneciton to use. + connectionToBundle = (WKConnectionRef)WKRetain(connection); +} + +/* WKConnectionClient */ +static void connectionDidReceiveMessage(WKConnectionRef connection, WKStringRef messageName, WKTypeRef messageBody, const void *clientInfo) +{ + // We only expect to get the "Pong" message. + EXPECT_WK_STREQ(messageName, "PongMessageName"); + EXPECT_WK_STREQ((WKStringRef)messageBody, "PongMessageBody"); + + messageReceived = true; +} + +static void connectionDidClose(WKConnectionRef connection, const void* clientInfo) +{ + connectionTornDown = true; +} + +TEST(WebKit2, WKConnectionTest) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, Util::createContextForInjectedBundleTest("WKConnectionTest")); + + // Set up the context's connection client so that we can access the connection when + // it is created. + WKContextConnectionClient contextConnectionClient; + memset(&contextConnectionClient, 0, sizeof(contextConnectionClient)); + contextConnectionClient.version = kWKContextConnectionClientCurrentVersion; + contextConnectionClient.clientInfo = 0; + contextConnectionClient.didCreateConnection = didCreateConnection; + WKContextSetConnectionClient(context.get(), &contextConnectionClient); + + // Load a simple page to start the WebProcess and establish a connection. + PlatformWebView webView(context.get()); + WKRetainPtr<WKURLRef> url(AdoptWK, Util::createURLForResource("simple", "html")); + WKPageLoadURL(webView.page(), url.get()); + + // Wait until the connection is established. + Util::run(&connectionEstablished); + ASSERT_NOT_NULL(connectionToBundle); + + // Setup a client on the connection so we can listen for messages and + // tear down notifications. + WKConnectionClient connectionClient; + memset(&connectionClient, 0, sizeof(connectionClient)); + connectionClient.version = WKConnectionClientCurrentVersion; + connectionClient.clientInfo = 0; + connectionClient.didReceiveMessage = connectionDidReceiveMessage; + connectionClient.didClose = connectionDidClose; + WKConnectionSetConnectionClient(connectionToBundle, &connectionClient); + + // Post a simple message to the bundle via the connection. + WKConnectionPostMessage(connectionToBundle, Util::toWK("PingMessageName").get(), Util::toWK("PingMessageBody").get()); + + // Wait for the reply. + Util::run(&messageReceived); + + // Terminate the page to force the connection closed. + WKPageTerminate(webView.page()); + + // Wait for the connection to close. + Util::run(&connectionTornDown); + + // This release is to balance the retain in didCreateConnection. + WKRelease(connectionToBundle); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/WKConnection_Bundle.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/WKConnection_Bundle.cpp new file mode 100644 index 000000000..9ab2c9768 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/WKConnection_Bundle.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "InjectedBundleTest.h" +#include "PlatformUtilities.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +/* WKConnectionClient */ +static void connectionDidReceiveMessage(WKConnectionRef connection, WKStringRef messageName, WKTypeRef messageBody, const void *clientInfo) +{ + // Post a simple message to the back to the application layer. + WKConnectionPostMessage(connection, Util::toWK("PongMessageName").get(), Util::toWK("PongMessageBody").get()); +} + +class WKConnectionTest : public InjectedBundleTest { +public: + WKConnectionTest(const std::string& identifier) + : InjectedBundleTest(identifier) + { + } + + virtual void initialize(WKBundleRef bundle, WKTypeRef) + { + WKConnectionClient connectionClient; + memset(&connectionClient, 0, sizeof(connectionClient)); + connectionClient.version = WKConnectionClientCurrentVersion; + connectionClient.clientInfo = 0; + connectionClient.didReceiveMessage = connectionDidReceiveMessage; + WKConnectionSetConnectionClient(WKBundleGetApplicationConnection(bundle), &connectionClient); + } +}; + +static InjectedBundleTest::Register<WKConnectionTest> registrar("WKConnectionTest"); + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/WKPreferences.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/WKPreferences.cpp new file mode 100644 index 000000000..8a0a7cfc5 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/WKPreferences.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include <WebKit2/WKPreferencesPrivate.h> +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +TEST(WebKit2, WKPreferencesBasic) +{ + WKPreferencesRef preference = WKPreferencesCreate(); + + EXPECT_EQ(WKPreferencesGetTypeID(), WKGetTypeID(preference)); + + WKRelease(preference); +} + +TEST(WebKit2, WKPreferencesDefaults) +{ +#if PLATFORM(WIN) + static const char* expectedStandardFontFamily = "Times New Roman"; + static const char* expectedFixedFontFamily = "Courier New"; + static const char* expectedSerifFontFamily = "Times New Roman"; + static const char* expectedSansSerifFontFamily = "Arial"; + static const char* expectedCursiveFontFamily = "Comic Sans MS"; + static const char* expectedFantasyFontFamily = "Comic Sans MS"; + static const char* expectedPictographFontFamily = "Times New Roman"; +#elif PLATFORM(MAC) + static const char* expectedStandardFontFamily = "Times"; + static const char* expectedFixedFontFamily = "Courier"; + static const char* expectedSerifFontFamily = "Times"; + static const char* expectedSansSerifFontFamily = "Helvetica"; + static const char* expectedCursiveFontFamily = "Apple Chancery"; + static const char* expectedFantasyFontFamily = "Papyrus"; + static const char* expectedPictographFontFamily = "Apple Color Emoji"; +#endif + + WKPreferencesRef preference = WKPreferencesCreate(); + + EXPECT_TRUE(WKPreferencesGetJavaScriptEnabled(preference)); + EXPECT_TRUE(WKPreferencesGetLoadsImagesAutomatically(preference)); + EXPECT_FALSE(WKPreferencesGetOfflineWebApplicationCacheEnabled(preference)); + EXPECT_TRUE(WKPreferencesGetLocalStorageEnabled(preference)); + EXPECT_TRUE(WKPreferencesGetXSSAuditorEnabled(preference)); + EXPECT_FALSE(WKPreferencesGetFrameFlatteningEnabled(preference)); + EXPECT_TRUE(WKPreferencesGetPluginsEnabled(preference)); + EXPECT_TRUE(WKPreferencesGetJavaEnabled(preference)); + EXPECT_TRUE(WKPreferencesGetJavaScriptCanOpenWindowsAutomatically(preference)); + EXPECT_TRUE(WKPreferencesGetHyperlinkAuditingEnabled(preference)); + EXPECT_WK_STREQ(expectedStandardFontFamily, adoptWK(WKPreferencesCopyStandardFontFamily(preference))); + EXPECT_WK_STREQ(expectedFixedFontFamily, adoptWK(WKPreferencesCopyFixedFontFamily(preference))); + EXPECT_WK_STREQ(expectedSerifFontFamily, adoptWK(WKPreferencesCopySerifFontFamily(preference))); + EXPECT_WK_STREQ(expectedSansSerifFontFamily, adoptWK(WKPreferencesCopySansSerifFontFamily(preference))); + EXPECT_WK_STREQ(expectedCursiveFontFamily, adoptWK(WKPreferencesCopyCursiveFontFamily(preference))); + EXPECT_WK_STREQ(expectedFantasyFontFamily, adoptWK(WKPreferencesCopyFantasyFontFamily(preference))); + EXPECT_WK_STREQ(expectedPictographFontFamily, adoptWK(WKPreferencesCopyPictographFontFamily(preference))); + EXPECT_EQ(0u, WKPreferencesGetMinimumFontSize(preference)); + EXPECT_FALSE(WKPreferencesGetPrivateBrowsingEnabled(preference)); + EXPECT_FALSE(WKPreferencesGetDeveloperExtrasEnabled(preference)); + EXPECT_TRUE(WKPreferencesGetTextAreasAreResizable(preference)); + +#if PLATFORM(WIN) + EXPECT_EQ(kWKFontSmoothingLevelWindows, WKPreferencesGetFontSmoothingLevel(preference)); +#else + EXPECT_EQ(kWKFontSmoothingLevelMedium, WKPreferencesGetFontSmoothingLevel(preference)); +#endif + + EXPECT_TRUE(WKPreferencesGetAcceleratedCompositingEnabled(preference)); + EXPECT_FALSE(WKPreferencesGetCompositingBordersVisible(preference)); + EXPECT_FALSE(WKPreferencesGetCompositingRepaintCountersVisible(preference)); + EXPECT_FALSE(WKPreferencesGetNeedsSiteSpecificQuirks(preference)); + + WKRelease(preference); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/WKString.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/WKString.cpp new file mode 100644 index 000000000..b67235932 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/WKString.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +namespace TestWebKitAPI { + +TEST(WebKit2, WKString) +{ + WKStringRef string = WKStringCreateWithUTF8CString("hello"); + EXPECT_TRUE(!WKStringIsEmpty(string)); + EXPECT_TRUE(WKStringIsEqual(string, string)); + EXPECT_TRUE(WKStringIsEqualToUTF8CString(string, "hello")); + EXPECT_EQ(16u, WKStringGetMaximumUTF8CStringSize(string)); + + size_t maxSize = WKStringGetMaximumUTF8CStringSize(string); + char* buffer = new char[maxSize]; + + size_t actualSize = WKStringGetUTF8CString(string, buffer, maxSize); + EXPECT_EQ(6u, actualSize); + EXPECT_STREQ("hello", buffer); + + delete[] buffer; + + maxSize = WKStringGetLength(string); + EXPECT_EQ(5u, maxSize); + + // Allocate a buffer one character larger than we need. + WKChar* uniBuffer = new WKChar[maxSize+1]; + actualSize = WKStringGetCharacters(string, uniBuffer, maxSize); + EXPECT_EQ(5u, actualSize); + + WKChar helloBuffer[] = { 'h', 'e', 'l', 'l', 'o' }; + EXPECT_TRUE(!memcmp(uniBuffer, helloBuffer, 10)); + + // Test passing a buffer length < the string length. + actualSize = WKStringGetCharacters(string, uniBuffer, maxSize - 1); + EXPECT_EQ(4u, actualSize); + + // Test passing a buffer length > the string length. + actualSize = WKStringGetCharacters(string, uniBuffer, maxSize + 1); + EXPECT_EQ(5u, actualSize); + + delete[] uniBuffer; + + WKRelease(string); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/WKStringJSString.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/WKStringJSString.cpp new file mode 100644 index 000000000..cdba57de4 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/WKStringJSString.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include <WebKit2/WKStringPrivate.h> +#include <JavaScriptCore/JSStringRef.h> + +namespace TestWebKitAPI { + +TEST(WebKit2, WKStringJSString) +{ + WKStringRef wkString = WKStringCreateWithUTF8CString("hello"); + JSStringRef jsString = JSStringCreateWithUTF8CString("hello"); + + WKStringRef convertedJSString = WKStringCreateWithJSString(jsString); + EXPECT_TRUE(WKStringIsEqual(wkString, convertedJSString)); + + JSStringRef convertedWKString = WKStringCopyJSString(wkString); + EXPECT_TRUE(JSStringIsEqual(jsString, convertedWKString)); + + WKRelease(wkString); + WKRelease(convertedJSString); + + JSStringRelease(jsString); + JSStringRelease(convertedWKString); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/WebArchive.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/WebArchive.cpp new file mode 100644 index 000000000..8ca13bc40 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/WebArchive.cpp @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include <CoreFoundation/CoreFoundation.h> +#include <WebKit2/WKURLCF.h> +#include <WebKit2/WKContextPrivate.h> +#include <wtf/RetainPtr.h> + +namespace TestWebKitAPI { + +static bool didFinishLoad; +static bool didReceiveMessage; + +static void didReceiveMessageFromInjectedBundle(WKContextRef, WKStringRef messageName, WKTypeRef body, const void*) +{ + didReceiveMessage = true; + + EXPECT_WK_STREQ("DidGetWebArchive", messageName); + EXPECT_TRUE(body); + EXPECT_EQ(WKDataGetTypeID(), WKGetTypeID(body)); + WKDataRef receivedData = static_cast<WKDataRef>(body); + + // Do basic sanity checks on the returned webarchive. We have more thorough checks in LayoutTests. + size_t size = WKDataGetSize(receivedData); + const unsigned char* bytes = WKDataGetBytes(receivedData); + RetainPtr<CFDataRef> data(AdoptCF, CFDataCreate(0, bytes, size)); + CFPropertyListFormat format = kCFPropertyListXMLFormat_v1_0 | kCFPropertyListBinaryFormat_v1_0; + RetainPtr<CFPropertyListRef> propertyList(AdoptCF, CFPropertyListCreateWithData(0, data.get(), kCFPropertyListImmutable, &format, 0)); + EXPECT_TRUE(propertyList); + + // It should be a dictionary. + EXPECT_EQ(CFDictionaryGetTypeID(), CFGetTypeID(propertyList.get())); + CFDictionaryRef dictionary = (CFDictionaryRef)propertyList.get(); + + // It should have a main resource. + CFTypeRef mainResource = CFDictionaryGetValue(dictionary, CFSTR("WebMainResource")); + EXPECT_TRUE(mainResource); + EXPECT_EQ(CFDictionaryGetTypeID(), CFGetTypeID(mainResource)); + CFDictionaryRef mainResourceDictionary = (CFDictionaryRef)mainResource; + + // Main resource should have a non-empty url and mime type. + CFTypeRef url = CFDictionaryGetValue(mainResourceDictionary, CFSTR("WebResourceURL")); + EXPECT_TRUE(url); + EXPECT_EQ(CFStringGetTypeID(), CFGetTypeID(url)); + EXPECT_NE(CFStringGetLength((CFStringRef)url), 0); + + CFTypeRef mimeType = CFDictionaryGetValue(mainResourceDictionary, CFSTR("WebResourceMIMEType")); + EXPECT_TRUE(mimeType); + EXPECT_EQ(CFStringGetTypeID(), CFGetTypeID(mimeType)); + EXPECT_NE(CFStringGetLength((CFStringRef)mimeType), 0); + + // Main resource dictionary should have a "WebResourceData" key. + CFTypeRef resourceData = CFDictionaryGetValue(mainResourceDictionary, CFSTR("WebResourceData")); + EXPECT_TRUE(resourceData); + EXPECT_EQ(CFDataGetTypeID(), CFGetTypeID(resourceData)); + + RetainPtr<CFStringRef> stringData(AdoptCF, CFStringCreateFromExternalRepresentation(0, (CFDataRef)resourceData, kCFStringEncodingUTF8)); + EXPECT_TRUE(stringData); + + // It should contain the string "Simple HTML file." in it. + bool foundString = CFStringFind(stringData.get(), CFSTR("Simple HTML file."), 0).location != kCFNotFound; + EXPECT_TRUE(foundString); +} + +static void setInjectedBundleClient(WKContextRef context) +{ + WKContextInjectedBundleClient injectedBundleClient; + memset(&injectedBundleClient, 0, sizeof(injectedBundleClient)); + injectedBundleClient.didReceiveMessageFromInjectedBundle = didReceiveMessageFromInjectedBundle; + + WKContextSetInjectedBundleClient(context, &injectedBundleClient); +} + +static void didFinishLoadForFrame(WKPageRef page, WKFrameRef, WKTypeRef, const void*) +{ + didFinishLoad = true; +} + +TEST(WebKit2, WebArchive) +{ + WKRetainPtr<WKContextRef> context = adoptWK(Util::createContextForInjectedBundleTest("WebArchiveTest")); + setInjectedBundleClient(context.get()); + + PlatformWebView webView(context.get()); + + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + + loaderClient.version = kWKPageLoaderClientCurrentVersion; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + WKPageSetPageLoaderClient(webView.page(), &loaderClient); + + WKPageLoadURL(webView.page(), adoptWK(Util::createURLForResource("simple", "html")).get()); + + // Wait till the load finishes before getting the web archive. + Util::run(&didFinishLoad); + WKContextPostMessageToInjectedBundle(context.get(), Util::toWK("GetWebArchive").get(), webView.page()); + + // Wait till we have received the web archive from the injected bundle. + Util::run(&didReceiveMessage); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/WebArchive_Bundle.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/WebArchive_Bundle.cpp new file mode 100644 index 000000000..f58859517 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/WebArchive_Bundle.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "InjectedBundleTest.h" + +#include "PlatformUtilities.h" +#include <WebKit2/WKBundlePage.h> +#include <WebKit2/WKBundleFrame.h> + +namespace TestWebKitAPI { + +class WebArchiveTest : public InjectedBundleTest { +public: + WebArchiveTest(const std::string& identifier); + +private: + virtual void didReceiveMessage(WKBundleRef, WKStringRef messageName, WKTypeRef messageBody); +}; + +static InjectedBundleTest::Register<WebArchiveTest> registrar("WebArchiveTest"); + +WebArchiveTest::WebArchiveTest(const std::string& identifier) + : InjectedBundleTest(identifier) +{ +} + +void WebArchiveTest::didReceiveMessage(WKBundleRef bundle, WKStringRef messageName, WKTypeRef body) +{ + if (!WKStringIsEqualToUTF8CString(messageName, "GetWebArchive")) + return; + + if (WKGetTypeID(body) != WKBundlePageGetTypeID()) + return; + + WKBundleFrameRef frame = WKBundlePageGetMainFrame(static_cast<WKBundlePageRef>(body)); + if (!frame) + return; + WKBundlePostMessage(bundle, Util::toWK("DidGetWebArchive").get(), adoptWK(WKBundleFrameCopyWebArchive(frame)).get()); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/file-with-anchor.html b/Tools/TestWebKitAPI/Tests/WebKit2/file-with-anchor.html new file mode 100644 index 000000000..8ea866ba9 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/file-with-anchor.html @@ -0,0 +1,19 @@ +<html> +<head> + <script> + function clickLink() + { + var evt = document.createEvent("MouseEvent"); + evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); + var link = document.querySelector('a'); + link.dispatchEvent(evt); + } + </script> +</head> +<body> + <a href="#anchor">Link to anchor</a><br> + In between.<br> + <span id="anchor">Anchor</span><br> + After the anchor.<br> + </body> +</html> diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/find.html b/Tools/TestWebKitAPI/Tests/WebKit2/find.html new file mode 100644 index 000000000..d9659119d --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/find.html @@ -0,0 +1,5 @@ +<html> +<body> + Test search. Hello Hello Hello! +</body> +</html> diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/icon.png b/Tools/TestWebKitAPI/Tests/WebKit2/icon.png Binary files differnew file mode 100644 index 000000000..79e459894 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/icon.png diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/mac/EditorCommands.mm b/Tools/TestWebKitAPI/Tests/WebKit2/mac/EditorCommands.mm new file mode 100644 index 000000000..583dc7a53 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/mac/EditorCommands.mm @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JavaScriptTest.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool didFinishLoad; + +static void didFinishLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef, const void*) +{ + didFinishLoad = true; +} + +TEST(WebKit2, ScrollByLineCommands) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, Util::createContextWithInjectedBundle()); + PlatformWebView webView(context.get()); + + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + loaderClient.version = 0; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + WKPageSetPageLoaderClient(webView.page(), &loaderClient); + + WKRetainPtr<WKURLRef> url(AdoptWK, Util::createURLForResource("simple-tall", "html")); + WKPageLoadURL(webView.page(), url.get()); + Util::run(&didFinishLoad); + + EXPECT_JS_EQ(webView.page(), "window.scrollY", "0"); + + ASSERT_TRUE([webView.platformView() respondsToSelector:@selector(scrollLineDown:)]); + [webView.platformView() scrollLineDown:nil]; + + EXPECT_JS_EQ(webView.page(), "window.scrollY", "40"); + + ASSERT_TRUE([webView.platformView() respondsToSelector:@selector(scrollLineUp:)]); + [webView.platformView() scrollLineUp:nil]; + + EXPECT_JS_EQ(webView.page(), "window.scrollY", "0"); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/mac/GetBackingScaleFactor.mm b/Tools/TestWebKitAPI/Tests/WebKit2/mac/GetBackingScaleFactor.mm new file mode 100644 index 000000000..4afd72fa2 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/mac/GetBackingScaleFactor.mm @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#import "config.h" + +#import "PlatformUtilities.h" +#import "SyntheticBackingScaleFactorWindow.h" +#import "Test.h" +#import <WebKit2/WKViewPrivate.h> +#import <wtf/RetainPtr.h> + +namespace TestWebKitAPI { + +static bool messageReceived; +static double backingScaleFactor; + +static void didReceiveMessageFromInjectedBundle(WKContextRef context, WKStringRef messageName, WKTypeRef messageBody, const void*) +{ + messageReceived = true; + EXPECT_WK_STREQ("DidGetBackingScaleFactor", messageName); + ASSERT_NOT_NULL(messageBody); + EXPECT_EQ(WKDoubleGetTypeID(), WKGetTypeID(messageBody)); + backingScaleFactor = WKDoubleGetValue(static_cast<WKDoubleRef>(messageBody)); +} + +static void setInjectedBundleClient(WKContextRef context) +{ + WKContextInjectedBundleClient injectedBundleClient; + memset(&injectedBundleClient, 0, sizeof(injectedBundleClient)); + injectedBundleClient.didReceiveMessageFromInjectedBundle = didReceiveMessageFromInjectedBundle; + WKContextSetInjectedBundleClient(context, &injectedBundleClient); +} + +static RetainPtr<SyntheticBackingScaleFactorWindow> createWindow() +{ + RetainPtr<SyntheticBackingScaleFactorWindow> window(AdoptNS, [[SyntheticBackingScaleFactorWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES]); + [window.get() setReleasedWhenClosed:NO]; + return window; +} + +TEST(WebKit2, GetBackingScaleFactor) +{ + WKRetainPtr<WKContextRef> context = adoptWK(Util::createContextForInjectedBundleTest("GetBackingScaleFactorTest")); + setInjectedBundleClient(context.get()); + RetainPtr<WKView> view(AdoptNS, [[WKView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) contextRef:context.get() pageGroupRef:0]); + + RetainPtr<SyntheticBackingScaleFactorWindow> window1 = createWindow(); + [window1.get() setBackingScaleFactor:1]; + + [[window1.get() contentView] addSubview:view.get()]; + WKContextPostMessageToInjectedBundle(context.get(), Util::toWK("GetBackingScaleFactor").get(), 0); + Util::run(&messageReceived); + messageReceived = false; + EXPECT_EQ(1, backingScaleFactor); + + RetainPtr<SyntheticBackingScaleFactorWindow> window2 = createWindow(); + [window2.get() setBackingScaleFactor:2]; + + [[window2.get() contentView] addSubview:view.get()]; + WKContextPostMessageToInjectedBundle(context.get(), Util::toWK("GetBackingScaleFactor").get(), 0); + Util::run(&messageReceived); + messageReceived = false; + EXPECT_EQ(2, backingScaleFactor); + + WKPageSetCustomBackingScaleFactor(view.get().pageRef, 3); + WKContextPostMessageToInjectedBundle(context.get(), Util::toWK("GetBackingScaleFactor").get(), 0); + Util::run(&messageReceived); + messageReceived = false; + EXPECT_EQ(3, backingScaleFactor); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/mac/GetBackingScaleFactor_Bundle.mm b/Tools/TestWebKitAPI/Tests/WebKit2/mac/GetBackingScaleFactor_Bundle.mm new file mode 100644 index 000000000..b8bceab48 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/mac/GetBackingScaleFactor_Bundle.mm @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#import "config.h" + +#import "InjectedBundleTest.h" +#import "PlatformUtilities.h" +#import <WebKit2/WKBundlePage.h> +#import <assert.h> + +namespace TestWebKitAPI { + +class GetBackingScaleFactorTest : public InjectedBundleTest { +public: + GetBackingScaleFactorTest(const std::string&); + +private: + virtual void didCreatePage(WKBundleRef, WKBundlePageRef); + virtual void didReceiveMessage(WKBundleRef, WKStringRef messageName, WKTypeRef messageBody); + + WKBundlePageRef m_page; +}; + +static InjectedBundleTest::Register<GetBackingScaleFactorTest> registrar("GetBackingScaleFactorTest"); + +GetBackingScaleFactorTest::GetBackingScaleFactorTest(const std::string& identifier) + : InjectedBundleTest(identifier) + , m_page(0) +{ +} + +void GetBackingScaleFactorTest::didCreatePage(WKBundleRef, WKBundlePageRef page) +{ + assert(!m_page); + m_page = page; +} + +void GetBackingScaleFactorTest::didReceiveMessage(WKBundleRef bundle, WKStringRef messageName, WKTypeRef messageBody) +{ + if (!WKStringIsEqualToUTF8CString(messageName, "GetBackingScaleFactor")) + return; + + WKRetainPtr<WKDoubleRef> backingScaleFactor = adoptWK(WKDoubleCreate(WKBundlePageGetBackingScaleFactor(m_page))); + WKBundlePostMessage(bundle, Util::toWK("DidGetBackingScaleFactor").get(), backingScaleFactor.get()); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/mouse-move-listener.html b/Tools/TestWebKitAPI/Tests/WebKit2/mouse-move-listener.html new file mode 100644 index 000000000..afca7ed86 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/mouse-move-listener.html @@ -0,0 +1,16 @@ +<!DOCTYPE html> +<script> + var mouseMoved = false; + + function mouseMoveHandler() + { + mouseMoved = true; + } + + function didMoveMouse() + { + return mouseMoved; + } + + addEventListener("mousemove", mouseMoveHandler); +</script> diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/push-state.html b/Tools/TestWebKitAPI/Tests/WebKit2/push-state.html new file mode 100644 index 000000000..f3a04a6bb --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/push-state.html @@ -0,0 +1,3 @@ +<script type="text/javascript"> +history.pushState('newState', 0, '?newState'); +</script> diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/simple-accelerated-compositing.html b/Tools/TestWebKitAPI/Tests/WebKit2/simple-accelerated-compositing.html new file mode 100644 index 000000000..bea62721b --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/simple-accelerated-compositing.html @@ -0,0 +1,5 @@ +<html> +<body> + <div style="-webkit-transform: translateZ(0);">Simple HTML file with accelerated compositing</div> +</body> +</html> diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/simple-form.html b/Tools/TestWebKitAPI/Tests/WebKit2/simple-form.html new file mode 100644 index 000000000..3bf185293 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/simple-form.html @@ -0,0 +1,11 @@ +<!DOCTYPE html> +<script> +function submitForm() +{ + document.forms[0].submit(); +} +</script> +<form method=post> +<input name=foo value="Some unimportant data"> +<input type=submit> +</form> diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/simple-iframe.html b/Tools/TestWebKitAPI/Tests/WebKit2/simple-iframe.html new file mode 100644 index 000000000..429521c7f --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/simple-iframe.html @@ -0,0 +1,6 @@ +<html> +<body> + Simple HTML file. + <iframe src="simple.html"></iframe> +</body> +</html> diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/simple-tall.html b/Tools/TestWebKitAPI/Tests/WebKit2/simple-tall.html new file mode 100644 index 000000000..a220e9b2d --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/simple-tall.html @@ -0,0 +1,7 @@ +<!DOCTYPE html> +<html> +<body> + Simple and tall HTML file. + <div style="height: 3000px;"></div> +</body> +</html> diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/simple.html b/Tools/TestWebKitAPI/Tests/WebKit2/simple.html new file mode 100644 index 000000000..12cf87364 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/simple.html @@ -0,0 +1,5 @@ +<html> +<body> + Simple HTML file. +</body> +</html> diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/spacebar-scrolling.html b/Tools/TestWebKitAPI/Tests/WebKit2/spacebar-scrolling.html new file mode 100644 index 000000000..8da08b3f9 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/spacebar-scrolling.html @@ -0,0 +1,26 @@ +<!DOCTYPE html> +<script> + function textFieldContainsSpace() + { + return document.querySelector("input").value === " "; + } + + function blurTextField() + { + document.querySelector("input").blur(); + } + + function isDocumentScrolled() + { + return scrollY !== 0; + } + + function loaded() + { + document.querySelector("input").focus(); + } + + addEventListener("load", loaded); +</script> +<input> +<div style="height: 3000px;"></div> diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/win/AltKeyGeneratesWMSysCommand.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/win/AltKeyGeneratesWMSysCommand.cpp new file mode 100644 index 000000000..000f9cdd0 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/win/AltKeyGeneratesWMSysCommand.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include "WindowMessageObserver.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +class WMSysCommandObserver : public WindowMessageObserver { +public: + WMSysCommandObserver() : m_windowDidReceiveWMSysCommand(false) { } + + bool windowDidReceiveWMSysCommand() const { return m_windowDidReceiveWMSysCommand; } + +private: + virtual void windowReceivedMessage(HWND, UINT message, WPARAM, LPARAM) + { + if (message == WM_SYSCOMMAND) + m_windowDidReceiveWMSysCommand = true; + } + + bool m_windowDidReceiveWMSysCommand; +}; + +static bool didNotHandleWMSysKeyUp; + +static void didNotHandleKeyEventCallback(WKPageRef, WKNativeEventPtr event, const void*) +{ + if (event->message != WM_SYSKEYUP) + return; + + didNotHandleWMSysKeyUp = true; +} + +TEST(WebKit2, AltKeyGeneratesWMSysCommand) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + PlatformWebView webView(context.get()); + + WKPageUIClient uiClient; + memset(&uiClient, 0, sizeof(uiClient)); + + uiClient.didNotHandleKeyEvent = didNotHandleKeyEventCallback; + WKPageSetPageUIClient(webView.page(), &uiClient); + + WMSysCommandObserver observer; + webView.setParentWindowMessageObserver(&observer); + + webView.simulateAltKeyPress(); + + Util::run(&didNotHandleWMSysKeyUp); + + webView.setParentWindowMessageObserver(0); + + // The WM_SYSKEYUP message should have generated a WM_SYSCOMMAND message that was sent to the + // WKView's parent window. + EXPECT_TRUE(observer.windowDidReceiveWMSysCommand()); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/win/DoNotCopyANullCFURLResponse.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/win/DoNotCopyANullCFURLResponse.cpp new file mode 100644 index 000000000..8bd0c5678 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/win/DoNotCopyANullCFURLResponse.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include <WebKit2/WKRetainPtr.h> +#include <WebKit2/WKURLResponseCF.h> +#include <wtf/RetainPtr.h> + +namespace TestWebKitAPI { + +TEST(WebKit2, DoNotCopyANullCFURLResponse) +{ + // Neither of these calls should cause a crash. + WKRetainPtr<WKURLResponseRef> nullWKResponse(AdoptWK, WKURLResponseCreateWithCFURLResponse(0)); + RetainPtr<CFURLResponseRef> nullCFResponse(AdoptCF, WKURLResponseCopyCFURLResponse(kCFAllocatorDefault, nullWKResponse.get())); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/win/HideFindIndicator.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/win/HideFindIndicator.cpp new file mode 100644 index 000000000..6e350ff81 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/win/HideFindIndicator.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include "Test.h" + +namespace TestWebKitAPI { + +static bool didFinishLoad; +static bool findIndicatorCallbackWasCalled; +static HBITMAP bitmap; + +static void didFinishLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) +{ + didFinishLoad = true; +} + +static void findIndicatorCallback(WKViewRef, HBITMAP selectionBitmap, RECT, bool, void*) +{ + findIndicatorCallbackWasCalled = true; + bitmap = selectionBitmap; +} + +static void initialize(const PlatformWebView& webView) +{ + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + + loaderClient.version = 0; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + WKPageSetPageLoaderClient(webView.page(), &loaderClient); + + WKViewSetFindIndicatorCallback(webView.platformView(), findIndicatorCallback, 0); +} + +TEST(WebKit2, HideFindIndicator) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + PlatformWebView webView(context.get()); + initialize(webView); + + WKRetainPtr<WKURLRef> url = adoptWK(Util::createURLForResource("find", "html")); + WKPageLoadURL(webView.page(), url.get()); + Util::run(&didFinishLoad); + didFinishLoad = false; + + WKPageFindString(webView.page(), Util::toWK("Hello").get(), kWKFindOptionsShowFindIndicator, 100); + Util::run(&findIndicatorCallbackWasCalled); + findIndicatorCallbackWasCalled = false; + + EXPECT_NOT_NULL(bitmap); + ::DeleteObject(bitmap); + bitmap = 0; + + WKPageHideFindUI(webView.page()); + Util::run(&findIndicatorCallbackWasCalled); + + EXPECT_NULL(bitmap); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/win/ResizeViewWhileHidden.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/win/ResizeViewWhileHidden.cpp new file mode 100644 index 000000000..32c8a0762 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/win/ResizeViewWhileHidden.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool didFinishLoad; + +static void didFinishLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef, const void*) +{ + didFinishLoad = true; +} + +static void setPageLoaderClient(WKPageRef page) +{ + WKPageLoaderClient loaderClient; + memset(&loaderClient, 0, sizeof(loaderClient)); + loaderClient.version = 0; + loaderClient.didFinishLoadForFrame = didFinishLoadForFrame; + + WKPageSetPageLoaderClient(page, &loaderClient); +} + +static void flushMessages(WKPageRef page) +{ + // In order to ensure all pending messages have been handled by the UI and web processes, we + // load a URL and wait for the load to finish. + + setPageLoaderClient(page); + + WKPageLoadURL(page, adoptWK(Util::createURLForResource("simple", "html")).get()); + Util::run(&didFinishLoad); + didFinishLoad = false; + + WKPageSetPageLoaderClient(page, 0); +} + +static bool timerFired; +static void CALLBACK timerCallback(HWND hwnd, UINT, UINT_PTR timerID, DWORD) +{ + ::KillTimer(hwnd, timerID); + timerFired = true; +} + +static void runForDuration(double seconds) +{ + ::SetTimer(0, 0, seconds * 1000, timerCallback); + Util::run(&timerFired); + timerFired = false; +} + +static void waitForBackingStoreUpdate(WKPageRef page) +{ + // Wait for the web process to handle the changes we just made, to perform a display (which + // happens on a timer), and to tell the UI process about the display (which updates the backing + // store). + // FIXME: It would be much less fragile (and maybe faster) to have an explicit way to wait + // until the backing store is updated. + runForDuration(0.5); + flushMessages(page); +} + +TEST(WebKit2, ResizeViewWhileHidden) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + PlatformWebView webView(context.get()); + + HWND window = WKViewGetWindow(webView.platformView()); + + RECT originalRect; + ::GetClientRect(window, &originalRect); + RECT newRect = originalRect; + ::InflateRect(&newRect, 1, 1); + + // Show the WKView and resize it so that the WKView's backing store will be created. Ideally + // we'd have some more explicit way of forcing the backing store to be created. + ::ShowWindow(window, SW_SHOW); + webView.resizeTo(newRect.right - newRect.left, newRect.bottom - newRect.top); + + waitForBackingStoreUpdate(webView.page()); + + // Resize the window while hidden and show it again so that it will update its backing store at + // the new size. + ::ShowWindow(window, SW_HIDE); + webView.resizeTo(originalRect.right - originalRect.left, originalRect.bottom - originalRect.top); + ::ShowWindow(window, SW_SHOW); + + // Force the WKView to paint to try to trigger <http://webkit.org/b/54142>. + ::SendMessage(window, WM_PAINT, 0, 0); + + // In Debug builds without the fix for <http://webkit.org/b/54141>, the web process will assert + // at this point. + // FIXME: It would be good to have a way to check that our behavior is correct in Release + // builds, too! + waitForBackingStoreUpdate(webView.page()); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/win/TranslateMessageGeneratesWMChar.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/win/TranslateMessageGeneratesWMChar.cpp new file mode 100644 index 000000000..844499cd6 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/win/TranslateMessageGeneratesWMChar.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include "WindowMessageObserver.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool didSeeWMChar; +static bool didNotHandleKeyEventCalled; + +static void didNotHandleKeyEventCallback(WKPageRef, WKNativeEventPtr event, const void*) +{ + if (event->message != WM_KEYDOWN) + return; + + // Don't call TranslateMessage() here so a WM_CHAR isn't generated. + didNotHandleKeyEventCalled = true; +} + +static void runAndWatchForWMChar(bool* done) +{ + while (!*done) { + MSG msg; + BOOL result = ::GetMessageW(&msg, 0, 0, 0); + if (!result || result == -1) + break; + + if (msg.message == WM_CHAR) + didSeeWMChar = true; + + if (Util::shouldTranslateMessage(msg)) + ::TranslateMessage(&msg); + + ::DispatchMessage(&msg); + } +} + +TEST(WebKit2, TranslateMessageGeneratesWMChar) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + PlatformWebView webView(context.get()); + + webView.simulateAKeyDown(); + + // WebKit should call TranslateMessage() on the WM_KEYDOWN message to generate the WM_CHAR message. + runAndWatchForWMChar(&didSeeWMChar); + + didSeeWMChar = false; + + WKPageUIClient uiClient; + memset(&uiClient, 0, sizeof(uiClient)); + + uiClient.didNotHandleKeyEvent = didNotHandleKeyEventCallback; + WKPageSetPageUIClient(webView.page(), &uiClient); + + webView.simulateAKeyDown(); + + runAndWatchForWMChar(&didNotHandleKeyEventCalled); + + // WebKit should not have called TranslateMessage() on the WM_KEYDOWN message since we installed a didNotHandleKeyEvent callback. + EXPECT_FALSE(didSeeWMChar); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/win/WMCloseCallsUIClientClose.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/win/WMCloseCallsUIClientClose.cpp new file mode 100644 index 000000000..5fa4b3a2a --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/win/WMCloseCallsUIClientClose.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +static bool didReceiveClose; + +static void close(WKPageRef, const void*) +{ + didReceiveClose = true; +} + +TEST(WebKit2, WMCloseCallsUIClientClose) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + PlatformWebView webView(context.get()); + + WKPageUIClient uiClient; + memset(&uiClient, 0, sizeof(uiClient)); + + uiClient.close = close; + WKPageSetPageUIClient(webView.page(), &uiClient); + + ::SendMessageW(WKViewGetWindow(webView.platformView()), WM_CLOSE, 0, 0); + + Util::run(&didReceiveClose); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/win/WMPrint.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/win/WMPrint.cpp new file mode 100644 index 000000000..36a18ca41 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2/win/WMPrint.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "PlatformUtilities.h" +#include "PlatformWebView.h" +#include <WebKit2/WKRetainPtr.h> + +namespace TestWebKitAPI { + +TEST(WebKit2, WMPrint) +{ + WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate()); + PlatformWebView webView(context.get()); + + HWND window = WKViewGetWindow(webView.platformView()); + HDC dc = ::CreateCompatibleDC(0); + // FIXME: It would be nice to test that this actually paints the view into dc. + ::SendMessage(window, WM_PRINT, reinterpret_cast<WPARAM>(dc), PRF_CLIENT | PRF_CHILDREN); + ::DeleteDC(dc); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/WebKit2ObjC/WKBrowsingContextGroupTest.mm b/Tools/TestWebKitAPI/Tests/WebKit2ObjC/WKBrowsingContextGroupTest.mm new file mode 100644 index 000000000..fbd87bdf4 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2ObjC/WKBrowsingContextGroupTest.mm @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#import "config.h" +#import "Test.h" + +#import <WebKit2/WKBrowsingContextGroup.h> + +TEST(WKBrowsingContextGroupTest, GetSetJavaScriptEnabled) +{ + WKBrowsingContextGroup *browsingContextGroup = [[WKBrowsingContextGroup alloc] initWithIdentifier:@"TestIdentifier"]; + + ASSERT_TRUE(browsingContextGroup.allowsJavaScript); + + browsingContextGroup.allowsJavaScript = NO; + + ASSERT_FALSE(browsingContextGroup.allowsJavaScript); + + [browsingContextGroup release]; +} + +TEST(WKBrowsingContextGroupTest, GetSetPluginsEnabled) +{ + WKBrowsingContextGroup *browsingContextGroup = [[WKBrowsingContextGroup alloc] initWithIdentifier:@"TestIdentifier"]; + + ASSERT_TRUE(browsingContextGroup.allowsPlugIns); + + browsingContextGroup.allowsPlugIns = NO; + + ASSERT_FALSE(browsingContextGroup.allowsPlugIns); + + [browsingContextGroup release]; +} diff --git a/Tools/TestWebKitAPI/Tests/WebKit2ObjC/WKBrowsingContextLoadDelegateTest.mm b/Tools/TestWebKitAPI/Tests/WebKit2ObjC/WKBrowsingContextLoadDelegateTest.mm new file mode 100644 index 000000000..f7f175d2e --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/WebKit2ObjC/WKBrowsingContextLoadDelegateTest.mm @@ -0,0 +1,138 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#import "config.h" +#import "Test.h" + +#import <WebKit2/WKBrowsingContextController.h> +#import <WebKit2/WKBrowsingContextGroup.h> +#import <WebKit2/WKBrowsingContextLoadDelegate.h> +#import <WebKit2/WKProcessGroup.h> +#import <WebKit2/WKRetainPtr.h> +#import <WebKit2/WKView.h> + +#import "PlatformUtilities.h" + +class WKBrowsingContextLoadDelegateTest : public ::testing::Test { +public: + WKProcessGroup *processGroup; + WKBrowsingContextGroup *browsingContextGroup; + WKView *view; + + WKBrowsingContextLoadDelegateTest() + : processGroup(nil) + , browsingContextGroup(nil) + , view(nil) + { + } + + virtual void SetUp() + { + processGroup = [[WKProcessGroup alloc] init]; + browsingContextGroup = [[WKBrowsingContextGroup alloc] initWithIdentifier:@"TestIdentifier"]; + view = [[WKView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) processGroup:processGroup browsingContextGroup:browsingContextGroup]; + } + + virtual void TearDown() + { + [view release]; + [browsingContextGroup release]; + [processGroup release]; + } +}; + + +static bool simpleLoadDone; + +@interface SimpleLoadDelegate : NSObject <WKBrowsingContextLoadDelegate> +@end + +@implementation SimpleLoadDelegate + +- (void)browsingContextControllerDidFinishLoad:(WKBrowsingContextController *)sender +{ + simpleLoadDone = true; +} + +@end + +TEST_F(WKBrowsingContextLoadDelegateTest, Empty) +{ + // Just make sure the setup/tear down works. +} + +TEST_F(WKBrowsingContextLoadDelegateTest, SimpleLoad) +{ + // Add the load delegate. + SimpleLoadDelegate *loadDelegate = [[SimpleLoadDelegate alloc] init]; + view.browsingContextController.loadDelegate = loadDelegate; + + // Load the file. + NSURL *nsURL = [[NSBundle mainBundle] URLForResource:@"simple" withExtension:@"html" subdirectory:@"TestWebKitAPI.resources"]; + [view.browsingContextController loadFileURL:nsURL restrictToFilesWithin:nil]; + + // Wait for the load to finish. + TestWebKitAPI::Util::run(&simpleLoadDone); + + // Tear down the delegate. + view.browsingContextController.loadDelegate = nil; + [loadDelegate release]; +} + + +static bool simpleLoadFailDone; + +@interface SimpleLoadFailDelegate : NSObject <WKBrowsingContextLoadDelegate> +@end + +@implementation SimpleLoadFailDelegate + +- (void)browsingContextControllerDidFailProvisionalLoad:(WKBrowsingContextController *)sender withError:(NSError *)error +{ + EXPECT_EQ(-1100, error.code); + EXPECT_WK_STREQ(NSURLErrorDomain, error.domain); + + simpleLoadFailDone = true; +} + +@end + +TEST_F(WKBrowsingContextLoadDelegateTest, SimpleLoadFail) +{ + // Add the load delegate. + SimpleLoadFailDelegate *loadDelegate = [[SimpleLoadFailDelegate alloc] init]; + view.browsingContextController.loadDelegate = loadDelegate; + + // Load a non-existent file. + NSURL *nsURL = [NSURL URLWithString:@"file:///does-not-exist.html"]; + [view.browsingContextController loadFileURL:nsURL restrictToFilesWithin:nil]; + + // Wait for the load to fail. + TestWebKitAPI::Util::run(&simpleLoadFailDone); + + // Tear down the delegate. + view.browsingContextController.loadDelegate = nil; + [loadDelegate release]; +} diff --git a/Tools/TestWebKitAPI/Tests/mac/DOMRangeOfString.html b/Tools/TestWebKitAPI/Tests/mac/DOMRangeOfString.html new file mode 100644 index 000000000..539cc0a53 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/mac/DOMRangeOfString.html @@ -0,0 +1,9 @@ +<!DOCTYPE html> +<html> +<body> + There is only a single needle in this stack of hay. + <iframe src="data:text/html, + There are no feathers in here. + "></iframe> +</body> +</html> diff --git a/Tools/TestWebKitAPI/Tests/mac/DOMRangeOfString.mm b/Tools/TestWebKitAPI/Tests/mac/DOMRangeOfString.mm new file mode 100644 index 000000000..1e8080539 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/mac/DOMRangeOfString.mm @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#import "config.h" +#import "PlatformUtilities.h" +#import <WebKit/WebViewPrivate.h> +#import <WebKit/DOM.h> +#import <wtf/RetainPtr.h> + +@interface DOMRangeOfStringFrameLoadDelegate : NSObject { +} +@end + +static bool didFinishLoad; + +@implementation DOMRangeOfStringFrameLoadDelegate + +- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame +{ + didFinishLoad = true; +} + +@end + +namespace TestWebKitAPI { + +TEST(WebKit1, DOMRangeOfString) +{ + RetainPtr<WebView> webView(AdoptNS, [[WebView alloc] initWithFrame:NSZeroRect frameName:nil groupName:nil]); + RetainPtr<DOMRangeOfStringFrameLoadDelegate> frameLoadDelegate(AdoptNS, [DOMRangeOfStringFrameLoadDelegate new]); + + webView.get().frameLoadDelegate = frameLoadDelegate.get(); + [[webView.get() mainFrame] loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"DOMRangeOfString" withExtension:@"html" subdirectory:@"TestWebKitAPI.resources"]]]; + + Util::run(&didFinishLoad); + + DOMRange *resultRange = [webView.get() DOMRangeOfString:@"needles" relativeTo:nil options:0]; + EXPECT_EQ(nil, resultRange); + + DOMRange *needleRange = [webView.get() DOMRangeOfString:@"needle" relativeTo:nil options:0]; + EXPECT_EQ(28, needleRange.startOffset); + + resultRange = [webView.get() DOMRangeOfString:@"stack" relativeTo:needleRange options:0]; + EXPECT_EQ(43, resultRange.startOffset); + + resultRange = [webView.get() DOMRangeOfString:@"stack" relativeTo:needleRange options:WebFindOptionsBackwards]; + EXPECT_EQ(nil, resultRange); + + resultRange = [webView.get() DOMRangeOfString:@"n" relativeTo:needleRange options:0]; + EXPECT_EQ(36, resultRange.startOffset); + + resultRange = [webView.get() DOMRangeOfString:@"n" relativeTo:needleRange options:WebFindOptionsStartInSelection]; + EXPECT_EQ(28, resultRange.startOffset); + + RetainPtr<WebView> otherWebView(AdoptNS, [[WebView alloc] initWithFrame:NSZeroRect frameName:nil groupName:nil]); + DOMRange *foreignRange = [[[otherWebView.get() mainFrame] DOMDocument] createRange]; + resultRange = [webView.get() DOMRangeOfString:@"needle" relativeTo:foreignRange options:0]; + EXPECT_EQ(nil, resultRange); + + resultRange = [webView.get() DOMRangeOfString:@"here" relativeTo:needleRange options:0]; + EXPECT_EQ(1, resultRange.startOffset); + + resultRange = [webView.get() DOMRangeOfString:@"here" relativeTo:resultRange options:0]; + EXPECT_EQ(25, resultRange.startOffset); + + resultRange = [webView.get() DOMRangeOfString:@"here" relativeTo:resultRange options:WebFindOptionsWrapAround]; + EXPECT_EQ(6, resultRange.startOffset); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/mac/DeviceScaleFactorOnBack.mm b/Tools/TestWebKitAPI/Tests/mac/DeviceScaleFactorOnBack.mm new file mode 100644 index 000000000..154b8c32c --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/mac/DeviceScaleFactorOnBack.mm @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WebKitAgnosticTest.h" + +#include "JavaScriptTest.h" +#include "PlatformUtilities.h" +#include "SyntheticBackingScaleFactorWindow.h" +#include <WebKit2/WKViewPrivate.h> +#include <wtf/RetainPtr.h> + +namespace TestWebKitAPI { + +class DeviceScaleFactorOnBack : public WebKitAgnosticTest { +public: + RetainPtr<SyntheticBackingScaleFactorWindow> createWindow(); + + template <typename View> void runTest(View); + + // WebKitAgnosticTest + virtual NSURL *url() const { return [[NSBundle mainBundle] URLForResource:@"devicePixelRatio" withExtension:@"html" subdirectory:@"TestWebKitAPI.resources"]; } + virtual void didLoadURL(WebView *webView) { runTest(webView); } + virtual void didLoadURL(WKView *wkView) { runTest(wkView); } + virtual void initializeView(WebView *); + virtual void initializeView(WKView *); +}; + +RetainPtr<SyntheticBackingScaleFactorWindow> DeviceScaleFactorOnBack::createWindow() +{ + RetainPtr<SyntheticBackingScaleFactorWindow> window(AdoptNS, [[SyntheticBackingScaleFactorWindow alloc] initWithContentRect:viewFrame styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES]); + [window.get() setReleasedWhenClosed:NO]; + return window; +} + +void DeviceScaleFactorOnBack::initializeView(WebView *view) +{ + // The default cache model has a capacity of 0, so it is necessary to switch to a cache + // model that actuall caches things. + [[view preferences] setCacheModel:WebCacheModelDocumentBrowser]; +} + +void DeviceScaleFactorOnBack::initializeView(WKView *view) +{ + // The default cache model has a capacity of 0, so it is necessary to switch to a cache + // model that actuall caches things. + WKContextSetCacheModel(WKPageGetContext([view pageRef]), kWKCacheModelDocumentBrowser); +} + +template <typename View> +void DeviceScaleFactorOnBack::runTest(View view) +{ + EXPECT_JS_EQ(view, "window.devicePixelRatio", "1"); + EXPECT_JS_EQ(view, "devicePixelRatioFromStyle()", "1"); + + // Navigate to new URL + loadURL(view, [NSURL URLWithString:@"about:blank"]); + waitForLoadToFinish(); + + // Change the scale factor + RetainPtr<SyntheticBackingScaleFactorWindow> window1 = createWindow(); + [window1.get() setBackingScaleFactor:3]; + + [[window1.get() contentView] addSubview:view]; + + // Navigate back to the first page + goBack(view); + waitForLoadToFinish(); + + // Ensure that the cached page has updated its scale factor + EXPECT_JS_EQ(view, "window.devicePixelRatio", "3"); + EXPECT_JS_EQ(view, "devicePixelRatioFromStyle()", "3"); + + [view removeFromSuperview]; +} + +TEST_F(DeviceScaleFactorOnBack, WebKit) +{ + runWebKit1Test(); +} + +TEST_F(DeviceScaleFactorOnBack, WebKit2) +{ + runWebKit2Test(); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/mac/DynamicDeviceScaleFactor.mm b/Tools/TestWebKitAPI/Tests/mac/DynamicDeviceScaleFactor.mm new file mode 100644 index 000000000..d0ebd5177 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/mac/DynamicDeviceScaleFactor.mm @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "WebKitAgnosticTest.h" + +#include "JavaScriptTest.h" +#include "PlatformUtilities.h" +#include "SyntheticBackingScaleFactorWindow.h" +#include <wtf/RetainPtr.h> + +namespace TestWebKitAPI { + +class DynamicDeviceScaleFactor : public WebKitAgnosticTest { +public: + RetainPtr<SyntheticBackingScaleFactorWindow> createWindow(); + + template <typename View> void runTest(View); + + // WebKitAgnosticTest + virtual NSURL *url() const { return [[NSBundle mainBundle] URLForResource:@"devicePixelRatio" withExtension:@"html" subdirectory:@"TestWebKitAPI.resources"]; } + virtual void didLoadURL(WebView *webView) { runTest(webView); } + virtual void didLoadURL(WKView *wkView) { runTest(wkView); } +}; + +RetainPtr<SyntheticBackingScaleFactorWindow> DynamicDeviceScaleFactor::createWindow() +{ + RetainPtr<SyntheticBackingScaleFactorWindow> window(AdoptNS, [[SyntheticBackingScaleFactorWindow alloc] initWithContentRect:viewFrame styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES]); + [window.get() setReleasedWhenClosed:NO]; + return window; +} + +template <typename View> +void DynamicDeviceScaleFactor::runTest(View view) +{ + EXPECT_JS_EQ(view, "window.devicePixelRatio", "1"); + EXPECT_JS_EQ(view, "devicePixelRatioFromStyle()", "1"); + + RetainPtr<SyntheticBackingScaleFactorWindow> window1 = createWindow(); + [window1.get() setBackingScaleFactor:3]; + + [[window1.get() contentView] addSubview:view]; + EXPECT_JS_EQ(view, "window.devicePixelRatio", "3"); + EXPECT_JS_EQ(view, "devicePixelRatioFromStyle()", "3"); + + RetainPtr<SyntheticBackingScaleFactorWindow> window2 = createWindow(); + [window2.get() setBackingScaleFactor:4]; + + [[window2.get() contentView] addSubview:view]; + EXPECT_JS_EQ(view, "window.devicePixelRatio", "4"); + EXPECT_JS_EQ(view, "devicePixelRatioFromStyle()", "4"); + + [view removeFromSuperview]; + EXPECT_JS_EQ(view, "window.devicePixelRatio", "1"); + EXPECT_JS_EQ(view, "devicePixelRatioFromStyle()", "1"); +} + +TEST_F(DynamicDeviceScaleFactor, WebKit) +{ + runWebKit1Test(); +} + +TEST_F(DynamicDeviceScaleFactor, WebKit2) +{ + runWebKit2Test(); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/mac/RenderedImageFromDOMRange.mm b/Tools/TestWebKitAPI/Tests/mac/RenderedImageFromDOMRange.mm new file mode 100644 index 000000000..4bda16798 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/mac/RenderedImageFromDOMRange.mm @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#import "config.h" +#import "PlatformUtilities.h" +#import <WebKit/WebDocumentPrivate.h> +#import <WebKit/DOMPrivate.h> +#import <wtf/RetainPtr.h> + +@interface RenderedImageFromDOMRangeFrameLoadDelegate : NSObject { +} +@end + +static bool didFinishLoad; + +@implementation RenderedImageFromDOMRangeFrameLoadDelegate + +- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame +{ + didFinishLoad = true; +} + +@end + +namespace TestWebKitAPI { + +TEST(WebKit1, RenderedImageFromDOMRange) +{ + RetainPtr<WebView> webView(AdoptNS, [[WebView alloc] initWithFrame:NSMakeRect(0, 0, 120, 200) frameName:nil groupName:nil]); + RetainPtr<RenderedImageFromDOMRangeFrameLoadDelegate> frameLoadDelegate(AdoptNS, [RenderedImageFromDOMRangeFrameLoadDelegate new]); + + webView.get().frameLoadDelegate = frameLoadDelegate.get(); + [webView.get().mainFrame loadHTMLString:@"<div style=\"width: 100px;\">Lorem <span id=\"target\">ipsum dolor</span> sit amet</div>" baseURL:[NSURL URLWithString:@"about:blank"]]; + + Util::run(&didFinishLoad); + + DOMDocument *document = webView.get().mainFrameDocument; + DOMRange *range = [document createRange]; + [range selectNode:[document getElementById:@"target"]]; + NSImage *actualImage = [range renderedImageForcingBlackText:YES]; + + [webView.get() setSelectedDOMRange:range affinity:NSSelectionAffinityDownstream]; + id <WebDocumentView> documentView = webView.get().mainFrame.frameView.documentView; + NSImage *expectedImage = [(id <WebDocumentSelection>)documentView selectionImageForcingBlackText:YES]; + EXPECT_TRUE([actualImage.TIFFRepresentation isEqual:expectedImage.TIFFRepresentation]); +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/mac/StringByEvaluatingJavaScriptFromString.mm b/Tools/TestWebKitAPI/Tests/mac/StringByEvaluatingJavaScriptFromString.mm new file mode 100644 index 000000000..1e64fb794 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/mac/StringByEvaluatingJavaScriptFromString.mm @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2007, 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#import "config.h" +#import "PlatformUtilities.h" +#import <wtf/RetainPtr.h> + +namespace TestWebKitAPI { + +TEST(WebKit1, StringByEvaluatingJavaScriptFromString) +{ + // maps expected result <= JavaScript expression + RetainPtr<NSDictionary> expressions(AdoptNS, [[NSDictionary alloc] initWithObjectsAndKeys: + @"0", @"0", + @"0", @"'0'", + @"", @"", + @"", @"''", + @"", @"new String()", + @"", @"new String('0')", + @"", @"throw 1", + @"", @"{ }", + @"", @"[ ]", + @"", @"//", + @"", @"a.b.c", + @"", @"(function() { throw 'error'; })()", + @"", @"null", + @"", @"undefined", + @"true", @"true", + @"false", @"false", + @"", @"alert('Should not be result')", + nil + ]); + + RetainPtr<WebView> webView (AdoptNS, [[WebView alloc] initWithFrame:NSZeroRect frameName:@"" groupName:@""]); + + for (id expression in expressions.get()) { + NSString *expectedResult = [expressions.get() objectForKey:expression]; + NSString *result = [webView.get() stringByEvaluatingJavaScriptFromString:expression]; + EXPECT_WK_STREQ(expectedResult, result); + } + + [webView.get() close]; +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/mac/SubresourceErrorCrash.mm b/Tools/TestWebKitAPI/Tests/mac/SubresourceErrorCrash.mm new file mode 100644 index 000000000..870a4896a --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/mac/SubresourceErrorCrash.mm @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2011 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +namespace TestWebKitAPI { + +TEST(WebKit1, SubresourceErrorCrash) +{ + WebView *webView = [[WebView alloc] initWithFrame:NSZeroRect frameName:@"" groupName:@""]; + [webView.mainFrame loadHTMLString:@"<link rel=stylesheet href='x-error:error'>" baseURL:nil]; + [webView release]; +} + +} // namespace TestWebKitAPI diff --git a/Tools/TestWebKitAPI/Tests/mac/devicePixelRatio.html b/Tools/TestWebKitAPI/Tests/mac/devicePixelRatio.html new file mode 100644 index 000000000..f6acf8678 --- /dev/null +++ b/Tools/TestWebKitAPI/Tests/mac/devicePixelRatio.html @@ -0,0 +1,23 @@ +<!DOCTYPE html> +<style> + #detector { width: 5px; } + @media (-webkit-device-pixel-ratio:1) { #detector { width: 10px; } } + @media (-webkit-device-pixel-ratio:3) { #detector { width: 30px; } } + @media (-webkit-device-pixel-ratio:4) { #detector { width: 40px; } } +</style> +<script> + function devicePixelRatioFromStyle() { + var width = getComputedStyle(document.getElementById("detector")).width; + switch (width) { + case "10px": + return 1; + case "30px": + return 3; + case "40px": + return 4; + default: + return "unknown width: " + width; + } + } +</script> +<div id="detector"></div> |
