this repo has no description
1// Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
2#include "Python.h"
3#include "gtest/gtest.h"
4
5#include "capi-fixture.h"
6#include "capi-testing.h"
7
8namespace py {
9namespace testing {
10
11using WeakRefExtensionApiTest = ExtensionApi;
12
13TEST_F(WeakRefExtensionApiTest, NewProxyWithCallbackReturnsProxy) {
14 PyRun_SimpleString(R"(
15class C:
16 def bar(self):
17 return "C.bar"
18
19def foo():
20 pass
21
22obj = C()
23)");
24 PyObjectPtr obj(mainModuleGet("obj"));
25 PyObjectPtr foo(mainModuleGet("foo"));
26 PyObjectPtr proxy(PyWeakref_NewProxy(obj, foo));
27 ASSERT_EQ(PyErr_Occurred(), nullptr);
28
29 PyObjectPtr result(PyObject_CallMethod(proxy, "bar", nullptr));
30 EXPECT_TRUE(isUnicodeEqualsCStr(result, "C.bar"));
31}
32
33TEST_F(WeakRefExtensionApiTest, NewProxyWithNullCallbackReturnsProxy) {
34 PyRun_SimpleString(R"(
35class C:
36 def bar(self):
37 return "C.bar"
38
39obj = C()
40)");
41 PyObjectPtr obj(mainModuleGet("obj"));
42 PyObjectPtr proxy(PyWeakref_NewProxy(obj, nullptr));
43 ASSERT_EQ(PyErr_Occurred(), nullptr);
44
45 PyObjectPtr result(PyObject_CallMethod(proxy, "bar", nullptr));
46 EXPECT_TRUE(isUnicodeEqualsCStr(result, "C.bar"));
47}
48
49TEST_F(WeakRefExtensionApiTest, NewWeakRefWithCallbackReturnsWeakRef) {
50 PyRun_SimpleString(R"(
51class C:
52 pass
53obj = C()
54def foo():
55 pass
56)");
57 PyObjectPtr obj(mainModuleGet("obj"));
58 PyObjectPtr foo(mainModuleGet("foo"));
59 PyObjectPtr ref(PyWeakref_NewRef(obj, foo));
60 EXPECT_TRUE(PyWeakref_Check(ref));
61}
62
63TEST_F(WeakRefExtensionApiTest, NewRefWithNullCallbackReturnsWeakRef) {
64 PyRun_SimpleString(R"(
65class C:
66 pass
67obj = C()
68def foo():
69 pass
70)");
71 PyObjectPtr obj(mainModuleGet("obj"));
72 PyObjectPtr ref(PyWeakref_NewRef(obj, nullptr));
73 EXPECT_TRUE(PyWeakref_Check(ref));
74}
75
76TEST_F(WeakRefExtensionApiTest, GetObjectWithNullRaisesSystemError) {
77 EXPECT_EQ(PyWeakref_GetObject(nullptr), nullptr);
78 ASSERT_NE(PyErr_Occurred(), nullptr);
79 EXPECT_TRUE(PyErr_ExceptionMatches(PyExc_SystemError));
80}
81
82TEST_F(WeakRefExtensionApiTest, GetObjectWithNonWeakrefRaisesSystemError) {
83 PyRun_SimpleString(R"(
84class C:
85 pass
86obj = C()
87def foo():
88 pass
89)");
90 PyObjectPtr obj(mainModuleGet("obj"));
91 EXPECT_EQ(PyWeakref_GetObject(obj), nullptr);
92 ASSERT_NE(PyErr_Occurred(), nullptr);
93 EXPECT_TRUE(PyErr_ExceptionMatches(PyExc_SystemError));
94}
95
96TEST_F(WeakRefExtensionApiTest, GetObjectReturnsReferent) {
97 PyRun_SimpleString(R"(
98class C:
99 pass
100obj = C()
101)");
102 PyObjectPtr obj(mainModuleGet("obj"));
103 PyObjectPtr ref(PyWeakref_NewRef(obj, nullptr));
104 PyObject* referent = PyWeakref_GetObject(ref);
105 EXPECT_EQ(referent, obj);
106}
107
108} // namespace testing
109} // namespace py