// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_UNITTESTS_TEST_UTILS_H_ #define V8_UNITTESTS_TEST_UTILS_H_ #include #include #include "include/v8.h" #include "src/api/api-inl.h" #include "src/base/macros.h" #include "src/base/utils/random-number-generator.h" #include "src/handles/handles.h" #include "src/objects/objects-inl.h" #include "src/objects/objects.h" #include "src/zone/accounting-allocator.h" #include "src/zone/zone.h" #include "testing/gtest-support.h" namespace v8 { class ArrayBufferAllocator; using CounterMap = std::map; enum CountersMode { kNoCounters, kEnableCounters }; // RAII-like Isolate instance wrapper. class IsolateWrapper final { public: explicit IsolateWrapper(CountersMode counters_mode); ~IsolateWrapper(); IsolateWrapper(const IsolateWrapper&) = delete; IsolateWrapper& operator=(const IsolateWrapper&) = delete; v8::Isolate* isolate() const { return isolate_; } private: std::unique_ptr array_buffer_allocator_; std::unique_ptr counter_map_; v8::Isolate* isolate_; }; // // A set of mixins from which the test fixtures will be constructed. // template class WithIsolateMixin : public TMixin { public: WithIsolateMixin() : isolate_wrapper_(kCountersMode) {} v8::Isolate* v8_isolate() const { return isolate_wrapper_.isolate(); } private: v8::IsolateWrapper isolate_wrapper_; }; template class WithIsolateScopeMixin : public TMixin { public: WithIsolateScopeMixin() : isolate_scope_(this->v8_isolate()), handle_scope_(this->v8_isolate()) {} WithIsolateScopeMixin(const WithIsolateScopeMixin&) = delete; WithIsolateScopeMixin& operator=(const WithIsolateScopeMixin&) = delete; v8::Isolate* isolate() const { return this->v8_isolate(); } v8::internal::Isolate* i_isolate() const { return reinterpret_cast(this->v8_isolate()); } private: v8::Isolate::Scope isolate_scope_; v8::HandleScope handle_scope_; }; template class WithContextMixin : public TMixin { public: WithContextMixin() : context_(Context::New(this->v8_isolate())), context_scope_(context_) {} WithContextMixin(const WithContextMixin&) = delete; WithContextMixin& operator=(const WithContextMixin&) = delete; const Local& context() const { return v8_context(); } const Local& v8_context() const { return context_; } Local RunJS(const char* source) { return RunJS( v8::String::NewFromUtf8(this->v8_isolate(), source).ToLocalChecked()); } Local RunJS(v8::String::ExternalOneByteStringResource* source) { return RunJS(v8::String::NewExternalOneByte(this->v8_isolate(), source) .ToLocalChecked()); } v8::Local NewString(const char* string) { return v8::String::NewFromUtf8(this->v8_isolate(), string).ToLocalChecked(); } void SetGlobalProperty(const char* name, v8::Local value) { CHECK(v8_context() ->Global() ->Set(v8_context(), NewString(name), value) .FromJust()); } private: Local RunJS(Local source) { auto context = this->v8_isolate()->GetCurrentContext(); Local