xref: /llvm-project/lldb/unittests/ScriptInterpreter/Python/PythonDataObjectsTests.cpp (revision f8b22f8fea181d2564267282e6c8249fde01bc13)
1 //===-- PythonDataObjectsTests.cpp ------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "gtest/gtest.h"
11 
12 #include "lldb/Host/HostInfo.h"
13 #include "Plugins/ScriptInterpreter/Python/lldb-python.h"
14 #include "Plugins/ScriptInterpreter/Python/PythonDataObjects.h"
15 #include "Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h"
16 
17 using namespace lldb_private;
18 
19 class PythonDataObjectsTest : public testing::Test
20 {
21   public:
22     void
23     SetUp() override
24     {
25         HostInfoBase::Initialize();
26         // ScriptInterpreterPython::Initialize() depends on HostInfo being
27         // initializedso it can compute the python directory etc.
28         ScriptInterpreterPython::Initialize();
29 
30         // Although we don't care about concurrency for the purposes of running
31         // this test suite, Python requires the GIL to be locked even for
32         // deallocating memory, which can happen when you call Py_DECREF or
33         // Py_INCREF.  So acquire the GIL for the entire duration of this
34         // test suite.
35         m_gil_state = PyGILState_Ensure();
36     }
37 
38     void
39     TearDown() override
40     {
41         PyGILState_Release(m_gil_state);
42 
43         ScriptInterpreterPython::Terminate();
44     }
45 
46   private:
47     PyGILState_STATE m_gil_state;
48 };
49 
50 TEST_F(PythonDataObjectsTest, TestOwnedReferences)
51 {
52     // After creating a new object, the refcount should be 1
53     PyObject *obj = PyLong_FromLong(3);
54     EXPECT_EQ(1, obj->ob_refcnt);
55 
56     // If we take an owned reference, the refcount should still be 1
57     PythonObject owned_long(PyRefType::Owned, obj);
58     EXPECT_EQ(1, owned_long.get()->ob_refcnt);
59 
60     // Take another reference and verify that the refcount increases
61     PythonObject strong_ref(owned_long);
62     EXPECT_EQ(2, strong_ref.get()->ob_refcnt);
63 
64     // If we reset the first one, the refcount should be 1 again.
65     owned_long.Reset();
66     EXPECT_EQ(1, strong_ref.get()->ob_refcnt);
67 }
68 
69 TEST_F(PythonDataObjectsTest, TestResetting)
70 {
71     PythonDictionary dict(PyInitialValue::Empty);
72 
73     PyObject *new_dict = PyDict_New();
74     dict.Reset(PyRefType::Owned, new_dict);
75     EXPECT_EQ(new_dict, dict.get());
76 
77     dict.Reset(PyRefType::Owned, nullptr);
78     EXPECT_EQ(nullptr, dict.get());
79 
80     dict.Reset(PyRefType::Owned, PyDict_New());
81     EXPECT_NE(nullptr, dict.get());
82     dict.Reset();
83     EXPECT_EQ(nullptr, dict.get());
84 }
85 
86 TEST_F(PythonDataObjectsTest, TestBorrowedReferences)
87 {
88     PythonInteger long_value(PyRefType::Owned, PyLong_FromLong(3));
89     EXPECT_EQ(1, long_value.get()->ob_refcnt);
90 
91     PythonInteger borrowed_long(PyRefType::Borrowed, long_value.get());
92     EXPECT_EQ(2, borrowed_long.get()->ob_refcnt);
93 }
94 
95 TEST_F(PythonDataObjectsTest, TestPythonInteger)
96 {
97 // Test that integers behave correctly when wrapped by a PythonInteger.
98 
99 #if PY_MAJOR_VERSION < 3
100     // Verify that `PythonInt` works correctly when given a PyInt object.
101     // Note that PyInt doesn't exist in Python 3.x, so this is only for 2.x
102     PyObject *py_int = PyInt_FromLong(12);
103     EXPECT_TRUE(PythonInteger::Check(py_int));
104     PythonInteger python_int(PyRefType::Owned, py_int);
105 
106     EXPECT_EQ(PyObjectType::Integer, python_int.GetObjectType());
107     EXPECT_EQ(12, python_int.GetInteger());
108 #endif
109 
110     // Verify that `PythonInt` works correctly when given a PyLong object.
111     PyObject *py_long = PyLong_FromLong(12);
112     EXPECT_TRUE(PythonInteger::Check(py_long));
113     PythonInteger python_long(PyRefType::Owned, py_long);
114     EXPECT_EQ(PyObjectType::Integer, python_long.GetObjectType());
115 
116     // Verify that you can reset the value and that it is reflected properly.
117     python_long.SetInteger(40);
118     EXPECT_EQ(40, python_long.GetInteger());
119 }
120 
121 TEST_F(PythonDataObjectsTest, TestPythonString)
122 {
123     // Test that strings behave correctly when wrapped by a PythonString.
124 
125     static const char *test_string = "PythonDataObjectsTest::TestPythonString";
126     static const char *test_string2 = "PythonDataObjectsTest::TestPythonString";
127 
128 #if PY_MAJOR_VERSION < 3
129     // Verify that `PythonString` works correctly when given a PyString object.
130     // Note that PyString doesn't exist in Python 3.x, so this is only for 2.x
131     PyObject *py_string = PyString_FromString(test_string);
132     EXPECT_TRUE(PythonString::Check(py_string));
133     PythonString python_string(PyRefType::Owned, py_string);
134 
135     EXPECT_EQ(PyObjectType::String, python_string.GetObjectType());
136     EXPECT_STREQ(test_string, python_string.GetString().data());
137 #endif
138 
139     // Verify that `PythonString` works correctly when given a PyUnicode object.
140     PyObject *py_unicode = PyUnicode_FromString(test_string);
141     EXPECT_TRUE(PythonString::Check(py_unicode));
142     PythonString python_unicode(PyRefType::Owned, py_unicode);
143 
144     EXPECT_EQ(PyObjectType::String, python_unicode.GetObjectType());
145     EXPECT_STREQ(test_string, python_unicode.GetString().data());
146 
147     // Verify that you can reset the value and that it is reflected properly.
148     python_unicode.SetString(test_string2);
149     EXPECT_STREQ(test_string2, python_unicode.GetString().data());
150 }
151 
152 TEST_F(PythonDataObjectsTest, TestPythonListPrebuilt)
153 {
154     // Test that a list which is built through the native
155     // Python API behaves correctly when wrapped by a PythonList.
156     static const int list_size = 2;
157     static const long long_idx0 = 5;
158     static const char *const string_idx1 = "String Index 1";
159 
160     PyObject *py_list = PyList_New(2);
161     EXPECT_TRUE(PythonList::Check(py_list));
162     PythonList list(PyRefType::Owned, py_list);
163 
164     PythonObject list_items[list_size];
165     list_items[0].Reset(PyRefType::Owned, PyLong_FromLong(long_idx0));
166     list_items[1].Reset(PyRefType::Owned, PyString_FromString(string_idx1));
167 
168     for (int i = 0; i < list_size; ++i)
169         list.SetItemAtIndex(i, list_items[i]);
170 
171     EXPECT_EQ(list_size, list.GetSize());
172     EXPECT_EQ(PyObjectType::List, list.GetObjectType());
173 
174     // PythonList doesn't yet support getting objects by type.
175     // For now, we have to call CreateStructuredArray and use
176     // those objects.  That will be in a different test.
177     // TODO: Add the ability for GetItemByIndex() to return a
178     // typed object.
179 }
180 
181 TEST_F(PythonDataObjectsTest, TestPythonDictionaryPrebuilt)
182 {
183     // Test that a dictionary which is built through the native
184     // Python API behaves correctly when wrapped by a PythonDictionary.
185     static const int dict_entries = 2;
186 
187     PythonObject keys[dict_entries];
188     PythonObject values[dict_entries];
189 
190     keys[0].Reset(PyRefType::Owned, PyString_FromString("Key 0"));
191     keys[1].Reset(PyRefType::Owned, PyLong_FromLong(1));
192     values[0].Reset(PyRefType::Owned, PyLong_FromLong(0));
193     values[1].Reset(PyRefType::Owned, PyString_FromString("Value 1"));
194 
195     PyObject *py_dict = PyDict_New();
196     EXPECT_TRUE(PythonDictionary::Check(py_dict));
197     PythonDictionary dict(PyRefType::Owned, py_dict);
198 
199     for (int i = 0; i < dict_entries; ++i)
200         PyDict_SetItem(py_dict, keys[i].get(), values[i].get());
201     EXPECT_EQ(dict.GetSize(), dict_entries);
202     EXPECT_EQ(PyObjectType::Dictionary, dict.GetObjectType());
203 
204     // PythonDictionary doesn't yet support getting objects by type.
205     // For now, we have to call CreateStructuredDictionary and use
206     // those objects.  That will be in a different test.
207     // TODO: Add the ability for GetItemByKey() to return a
208     // typed object.
209 }
210 
211 TEST_F(PythonDataObjectsTest, TestPythonListManipulation)
212 {
213     // Test that manipulation of a PythonList behaves correctly when
214     // wrapped by a PythonDictionary.
215 
216     static const long long_idx0 = 5;
217     static const char *const string_idx1 = "String Index 1";
218 
219     PythonList list(PyInitialValue::Empty);
220     PythonInteger integer(long_idx0);
221     PythonString string(string_idx1);
222 
223     list.AppendItem(integer);
224     list.AppendItem(string);
225     EXPECT_EQ(2, list.GetSize());
226 
227     // PythonList doesn't yet support getting typed objects out, so we
228     // can't easily test that the first item is an integer with the correct
229     // value, etc.
230     // TODO: Add the ability for GetItemByIndex() to return a
231     // typed object.
232 }
233 
234 TEST_F(PythonDataObjectsTest, TestPythonDictionaryManipulation)
235 {
236     // Test that manipulation of a dictionary behaves correctly when wrapped
237     // by a PythonDictionary.
238     static const int dict_entries = 2;
239 
240     PythonString keys[dict_entries];
241     PythonObject values[dict_entries];
242 
243     keys[0].Reset(PyRefType::Owned, PyString_FromString("Key 0"));
244     keys[1].Reset(PyRefType::Owned, PyString_FromString("Key 1"));
245     values[0].Reset(PyRefType::Owned, PyLong_FromLong(1));
246     values[1].Reset(PyRefType::Owned, PyString_FromString("Value 1"));
247 
248     PythonDictionary dict(PyInitialValue::Empty);
249     for (int i = 0; i < 2; ++i)
250         dict.SetItemForKey(keys[i], values[i]);
251 
252     EXPECT_EQ(dict_entries, dict.GetSize());
253 
254     // PythonDictionary doesn't yet support getting objects by type.
255     // For now, we have to call CreateStructuredDictionary and use
256     // those objects.  That will be in a different test.
257     // TODO: Add the ability for GetItemByKey() to return a
258     // typed object.
259 }
260 
261 TEST_F(PythonDataObjectsTest, TestPythonListToStructuredObject)
262 {
263     // Test that a PythonList is properly converted to a StructuredArray.
264     // This includes verifying that a list can contain a nested list as
265     // well as a nested dictionary.
266 
267     static const int item_count = 4;
268     static const long long_idx0 = 5;
269     static const char *const string_idx1 = "String Index 1";
270 
271     static const long nested_list_long_idx0 = 6;
272     static const char *const nested_list_str_idx1 = "Nested String Index 1";
273 
274     static const char *const nested_dict_key0 = "Nested Key 0";
275     static const char *const nested_dict_value0 = "Nested Value 0";
276     static const char *const nested_dict_key1 = "Nested Key 1";
277     static const long nested_dict_value1 = 2;
278 
279     PythonList list(PyInitialValue::Empty);
280     PythonList nested_list(PyInitialValue::Empty);
281     PythonDictionary nested_dict(PyInitialValue::Empty);
282 
283     nested_list.AppendItem(PythonInteger(nested_list_long_idx0));
284     nested_list.AppendItem(PythonString(nested_list_str_idx1));
285     nested_dict.SetItemForKey(PythonString(nested_dict_key0), PythonString(nested_dict_value0));
286     nested_dict.SetItemForKey(PythonString(nested_dict_key1), PythonInteger(nested_dict_value1));
287 
288     list.AppendItem(PythonInteger(long_idx0));
289     list.AppendItem(PythonString(string_idx1));
290     list.AppendItem(nested_list);
291     list.AppendItem(nested_dict);
292 
293     EXPECT_EQ(item_count, list.GetSize());
294 
295     StructuredData::ArraySP array_sp = list.CreateStructuredArray();
296     EXPECT_EQ(list.GetSize(), array_sp->GetSize());
297     EXPECT_EQ(StructuredData::Type::eTypeInteger, array_sp->GetItemAtIndex(0)->GetType());
298     EXPECT_EQ(StructuredData::Type::eTypeString, array_sp->GetItemAtIndex(1)->GetType());
299     EXPECT_EQ(StructuredData::Type::eTypeArray, array_sp->GetItemAtIndex(2)->GetType());
300     EXPECT_EQ(StructuredData::Type::eTypeDictionary, array_sp->GetItemAtIndex(3)->GetType());
301 
302     auto list_int_sp = std::static_pointer_cast<StructuredData::Integer>(array_sp->GetItemAtIndex(0));
303     auto list_str_sp = std::static_pointer_cast<StructuredData::String>(array_sp->GetItemAtIndex(1));
304     auto list_list_sp = std::static_pointer_cast<StructuredData::Array>(array_sp->GetItemAtIndex(2));
305     auto list_dict_sp = std::static_pointer_cast<StructuredData::Dictionary>(array_sp->GetItemAtIndex(3));
306 
307     // Verify that the first item (long) has the correct value
308     EXPECT_EQ(long_idx0, list_int_sp->GetValue());
309 
310     // Verify that the second item (string) has the correct value
311     EXPECT_STREQ(string_idx1, list_str_sp->GetValue().c_str());
312 
313     // Verify that the third item is a list with the correct length and element types
314     EXPECT_EQ(nested_list.GetSize(), list_list_sp->GetSize());
315     EXPECT_EQ(StructuredData::Type::eTypeInteger, list_list_sp->GetItemAtIndex(0)->GetType());
316     EXPECT_EQ(StructuredData::Type::eTypeString, list_list_sp->GetItemAtIndex(1)->GetType());
317     // Verify that the values of each element in the list are correct
318     auto nested_list_value_0 = std::static_pointer_cast<StructuredData::Integer>(list_list_sp->GetItemAtIndex(0));
319     auto nested_list_value_1 = std::static_pointer_cast<StructuredData::String>(list_list_sp->GetItemAtIndex(1));
320     EXPECT_EQ(nested_list_long_idx0, nested_list_value_0->GetValue());
321     EXPECT_STREQ(nested_list_str_idx1, nested_list_value_1->GetValue().c_str());
322 
323     // Verify that the fourth item is a dictionary with the correct length
324     EXPECT_EQ(nested_dict.GetSize(), list_dict_sp->GetSize());
325     auto dict_keys = std::static_pointer_cast<StructuredData::Array>(list_dict_sp->GetKeys());
326 
327     // Verify that all of the keys match the values and types of keys we inserted
328     EXPECT_EQ(StructuredData::Type::eTypeString, dict_keys->GetItemAtIndex(0)->GetType());
329     EXPECT_EQ(StructuredData::Type::eTypeString, dict_keys->GetItemAtIndex(1)->GetType());
330     auto nested_key_0 = std::static_pointer_cast<StructuredData::String>(dict_keys->GetItemAtIndex(0));
331     auto nested_key_1 = std::static_pointer_cast<StructuredData::String>(dict_keys->GetItemAtIndex(1));
332     EXPECT_STREQ(nested_dict_key0, nested_key_0->GetValue().c_str());
333     EXPECT_STREQ(nested_dict_key1, nested_key_1->GetValue().c_str());
334 
335     // Verify that for each key, the value has the correct type and value as what we inserted.
336     auto nested_dict_value_0 = list_dict_sp->GetValueForKey(nested_key_0->GetValue());
337     auto nested_dict_value_1 = list_dict_sp->GetValueForKey(nested_key_1->GetValue());
338     EXPECT_EQ(StructuredData::Type::eTypeString, nested_dict_value_0->GetType());
339     EXPECT_EQ(StructuredData::Type::eTypeInteger, nested_dict_value_1->GetType());
340     auto nested_dict_str_value_0 = std::static_pointer_cast<StructuredData::String>(nested_dict_value_0);
341     auto nested_dict_int_value_1 = std::static_pointer_cast<StructuredData::Integer>(nested_dict_value_1);
342     EXPECT_STREQ(nested_dict_value0, nested_dict_str_value_0->GetValue().c_str());
343     EXPECT_EQ(nested_dict_value1, nested_dict_int_value_1->GetValue());
344 }
345 
346 TEST_F(PythonDataObjectsTest, TestPythonDictionaryToStructuredObject)
347 {
348     // Test that a PythonDictionary is properly converted to a
349     // StructuredDictionary.  This includes verifying that a dictionary
350     // can contain a nested dictionary as well as a nested list.
351 
352     static const int dict_item_count = 4;
353     static const char *const dict_keys[dict_item_count] = {"Key 0 (str)", "Key 1 (long)", "Key 2 (dict)",
354                                                            "Key 3 (list)"};
355 
356     static const StructuredData::Type dict_value_types[dict_item_count] = {
357         StructuredData::Type::eTypeString, StructuredData::Type::eTypeInteger, StructuredData::Type::eTypeDictionary,
358         StructuredData::Type::eTypeArray};
359 
360     static const char *const nested_dict_keys[2] = {"Nested Key 0 (str)", "Nested Key 1 (long)"};
361 
362     static const StructuredData::Type nested_dict_value_types[2] = {
363         StructuredData::Type::eTypeString, StructuredData::Type::eTypeInteger,
364     };
365 
366     static const StructuredData::Type nested_list_value_types[2] = {StructuredData::Type::eTypeInteger,
367                                                                     StructuredData::Type::eTypeString};
368 
369     static const char *const dict_value0 = "Value 0";
370     static const long dict_value1 = 2;
371 
372     static const long nested_list_value0 = 5;
373     static const char *const nested_list_value1 = "Nested list string";
374 
375     static const char *const nested_dict_value0 = "Nested Dict Value 0";
376     static const long nested_dict_value1 = 7;
377 
378     PythonDictionary dict(PyInitialValue::Empty);
379     PythonDictionary nested_dict(PyInitialValue::Empty);
380     PythonList nested_list(PyInitialValue::Empty);
381 
382     nested_dict.SetItemForKey(PythonString(nested_dict_keys[0]), PythonString(nested_dict_value0));
383     nested_dict.SetItemForKey(PythonString(nested_dict_keys[1]), PythonInteger(nested_dict_value1));
384 
385     nested_list.AppendItem(PythonInteger(nested_list_value0));
386     nested_list.AppendItem(PythonString(nested_list_value1));
387 
388     dict.SetItemForKey(PythonString(dict_keys[0]), PythonString(dict_value0));
389     dict.SetItemForKey(PythonString(dict_keys[1]), PythonInteger(dict_value1));
390     dict.SetItemForKey(PythonString(dict_keys[2]), nested_dict);
391     dict.SetItemForKey(PythonString(dict_keys[3]), nested_list);
392 
393     StructuredData::DictionarySP dict_sp = dict.CreateStructuredDictionary();
394     EXPECT_EQ(dict_item_count, dict_sp->GetSize());
395     auto dict_keys_array = std::static_pointer_cast<StructuredData::Array>(dict_sp->GetKeys());
396 
397     std::vector<StructuredData::StringSP> converted_keys;
398     std::vector<StructuredData::ObjectSP> converted_values;
399     // Verify that all of the keys match the values and types of keys we inserted
400     // (Keys are always strings, so this is easy)
401     for (int i = 0; i < dict_sp->GetSize(); ++i)
402     {
403         EXPECT_EQ(StructuredData::Type::eTypeString, dict_keys_array->GetItemAtIndex(i)->GetType());
404         auto converted_key = std::static_pointer_cast<StructuredData::String>(dict_keys_array->GetItemAtIndex(i));
405         converted_keys.push_back(converted_key);
406         converted_values.push_back(dict_sp->GetValueForKey(converted_key->GetValue().c_str()));
407 
408         EXPECT_STREQ(dict_keys[i], converted_key->GetValue().c_str());
409         EXPECT_EQ(dict_value_types[i], converted_values[i]->GetType());
410     }
411 
412     auto dict_string_value = std::static_pointer_cast<StructuredData::String>(converted_values[0]);
413     auto dict_int_value = std::static_pointer_cast<StructuredData::Integer>(converted_values[1]);
414     auto dict_dict_value = std::static_pointer_cast<StructuredData::Dictionary>(converted_values[2]);
415     auto dict_list_value = std::static_pointer_cast<StructuredData::Array>(converted_values[3]);
416 
417     // The first two dictionary values are easy to test, because they are just a string and an integer.
418     EXPECT_STREQ(dict_value0, dict_string_value->GetValue().c_str());
419     EXPECT_EQ(dict_value1, dict_int_value->GetValue());
420 
421     // For the nested dictionary, repeat the same process as before.
422     EXPECT_EQ(2, dict_dict_value->GetSize());
423     auto nested_dict_keys_array = std::static_pointer_cast<StructuredData::Array>(dict_dict_value->GetKeys());
424 
425     std::vector<StructuredData::StringSP> nested_converted_keys;
426     std::vector<StructuredData::ObjectSP> nested_converted_values;
427     // Verify that all of the keys match the values and types of keys we inserted
428     // (Keys are always strings, so this is easy)
429     for (int i = 0; i < dict_dict_value->GetSize(); ++i)
430     {
431         EXPECT_EQ(StructuredData::Type::eTypeString, nested_dict_keys_array->GetItemAtIndex(i)->GetType());
432         auto converted_key =
433             std::static_pointer_cast<StructuredData::String>(nested_dict_keys_array->GetItemAtIndex(i));
434         nested_converted_keys.push_back(converted_key);
435         nested_converted_values.push_back(dict_dict_value->GetValueForKey(converted_key->GetValue().c_str()));
436 
437         EXPECT_STREQ(nested_dict_keys[i], converted_key->GetValue().c_str());
438         EXPECT_EQ(nested_dict_value_types[i], converted_values[i]->GetType());
439     }
440 
441     auto converted_nested_dict_value_0 = std::static_pointer_cast<StructuredData::String>(nested_converted_values[0]);
442     auto converted_nested_dict_value_1 = std::static_pointer_cast<StructuredData::Integer>(nested_converted_values[1]);
443 
444     // The first two dictionary values are easy to test, because they are just a string and an integer.
445     EXPECT_STREQ(nested_dict_value0, converted_nested_dict_value_0->GetValue().c_str());
446     EXPECT_EQ(nested_dict_value1, converted_nested_dict_value_1->GetValue());
447 
448     // For the nested list, just verify the size, type and value of each item
449     nested_converted_values.clear();
450     EXPECT_EQ(2, dict_list_value->GetSize());
451     for (int i = 0; i < dict_list_value->GetSize(); ++i)
452     {
453         auto converted_value = dict_list_value->GetItemAtIndex(i);
454         EXPECT_EQ(nested_list_value_types[i], converted_value->GetType());
455         nested_converted_values.push_back(converted_value);
456     }
457 
458     auto converted_nested_list_value_0 = std::static_pointer_cast<StructuredData::Integer>(nested_converted_values[0]);
459     auto converted_nested_list_value_1 = std::static_pointer_cast<StructuredData::String>(nested_converted_values[1]);
460     EXPECT_EQ(nested_list_value0, converted_nested_list_value_0->GetValue());
461     EXPECT_STREQ(nested_list_value1, converted_nested_list_value_1->GetValue().c_str());
462 }
463