File
Blob: src/workerd/jsg/struct-test.c++
| 1 | // Copyright (c) 2017-2022 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | |
| 5 | #include "jsg-test.h" |
| 6 | |
| 7 | namespace workerd::jsg::test { |
| 8 | namespace { |
| 9 | |
| 10 | V8System v8System; |
| 11 | |
| 12 | struct SelfStruct { |
| 13 | SelfRef self; |
| 14 | int i; |
| 15 | |
| 16 | JSG_STRUCT(self, i); |
| 17 | }; |
| 18 | |
| 19 | struct StructContext: public Object, public ContextGlobal { |
| 20 | kj::String readTestStruct(TestStruct s) { |
| 21 | return kj::str(s.str, ", ", s.num, ", ", s.box->value); |
| 22 | } |
| 23 | TestStruct makeTestStruct(jsg::Lock& js, kj::String str, double num, NumberBox& box) { |
| 24 | return {kj::mv(str), num, js.alloc<NumberBox>(box.value)}; |
| 25 | } |
| 26 | V8Ref<v8::Object> readSelfStruct(Lock& js, SelfStruct s) { |
| 27 | KJ_ASSERT(s.i == 123); |
| 28 | return kj::mv(s.self); |
| 29 | } |
| 30 | SelfStruct makeSelfStruct(Lock& js) { |
| 31 | return {.self = {js.v8Isolate, v8::Object::New(js.v8Isolate)}, .i = 456}; |
| 32 | } |
| 33 | |
| 34 | JSG_RESOURCE_TYPE(StructContext) { |
| 35 | JSG_NESTED_TYPE(NumberBox); |
| 36 | JSG_METHOD(readTestStruct); |
| 37 | JSG_METHOD(makeTestStruct); |
| 38 | JSG_METHOD(readSelfStruct); |
| 39 | JSG_METHOD(makeSelfStruct); |
| 40 | } |
| 41 | }; |
| 42 | JSG_DECLARE_ISOLATE_TYPE(StructIsolate, StructContext, NumberBox, TestStruct, SelfStruct); |
| 43 | |
| 44 | KJ_TEST("structs") { |
| 45 | Evaluator<StructContext, StructIsolate> e(v8System); |
| 46 | e.expectEval( |
| 47 | "readTestStruct({str: 'foo', num: 123, box: new NumberBox(456)})", "string", "foo, 123, 456"); |
| 48 | e.expectEval("var s = makeTestStruct('foo', 123, new NumberBox(456));\n" |
| 49 | "[s.str, s.num, s.box.value].join(', ')", |
| 50 | "string", "foo, 123, 456"); |
| 51 | |
| 52 | e.expectEval("readTestStruct({str: 'foo', num: 123, box: 'wrong'})", "throws", |
| 53 | "TypeError: Incorrect type for the 'box' field on 'TestStruct': the provided " |
| 54 | "value is not of type 'NumberBox'."); |
| 55 | |
| 56 | e.expectEval( |
| 57 | "JSON.stringify(readSelfStruct({i: 123, x: 'foo'}))", "string", "{\"i\":123,\"x\":\"foo\"}"); |
| 58 | e.expectEval("JSON.stringify(makeSelfStruct())", "string", "{\"i\":456}"); |
| 59 | } |
| 60 | |
| 61 | } // namespace |
| 62 | } // namespace workerd::jsg::test |