xref: /llvm-project/lldb/unittests/ScriptInterpreter/Python/PythonDataObjectsTests.cpp (revision c86a6acaee55c98072ff06d372d049cb4a671fb5)
1 //===-- PythonDataObjectsTests.cpp ------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Plugins/ScriptInterpreter/Python/lldb-python.h"
10 #include "gtest/gtest.h"
11 
12 #include "Plugins/ScriptInterpreter/Python/PythonDataObjects.h"
13 #include "Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.h"
14 #include "lldb/Host/File.h"
15 #include "lldb/Host/FileSystem.h"
16 #include "lldb/Host/HostInfo.h"
17 #include "lldb/lldb-enumerations.h"
18 #include "llvm/Testing/Support/Error.h"
19 
20 #include "PythonTestSuite.h"
21 
22 using namespace lldb_private;
23 using namespace lldb_private::python;
24 
25 class PythonDataObjectsTest : public PythonTestSuite {
26 public:
27   void SetUp() override {
28     PythonTestSuite::SetUp();
29 
30     PythonString sys_module("sys");
31     m_sys_module.Reset(PyRefType::Owned, PyImport_Import(sys_module.get()));
32     m_main_module = PythonModule::MainModule();
33     m_builtins_module = PythonModule::BuiltinsModule();
34   }
35 
36   void TearDown() override {
37     m_sys_module.Reset();
38     m_main_module.Reset();
39     m_builtins_module.Reset();
40 
41     PythonTestSuite::TearDown();
42   }
43 
44 protected:
45   PythonModule m_sys_module;
46   PythonModule m_main_module;
47   PythonModule m_builtins_module;
48 };
49 
50 TEST_F(PythonDataObjectsTest, TestOwnedReferences) {
51   // After creating a new object, the refcount should be >= 1
52   PyObject *obj = PyLong_FromLong(3);
53   Py_ssize_t original_refcnt = obj->ob_refcnt;
54   EXPECT_LE(1, original_refcnt);
55 
56   // If we take an owned reference, the refcount should be the same
57   PythonObject owned_long(PyRefType::Owned, obj);
58   EXPECT_EQ(original_refcnt, owned_long.get()->ob_refcnt);
59 
60   // Take another reference and verify that the refcount increases by 1
61   PythonObject strong_ref(owned_long);
62   EXPECT_EQ(original_refcnt + 1, strong_ref.get()->ob_refcnt);
63 
64   // If we reset the first one, the refcount should be the original value.
65   owned_long.Reset();
66   EXPECT_EQ(original_refcnt, strong_ref.get()->ob_refcnt);
67 }
68 
69 TEST_F(PythonDataObjectsTest, TestResetting) {
70   PythonDictionary dict(PyInitialValue::Empty);
71 
72   PyObject *new_dict = PyDict_New();
73   dict.Reset(PyRefType::Owned, new_dict);
74   EXPECT_EQ(new_dict, dict.get());
75 
76   dict.Reset(PyRefType::Owned, nullptr);
77   EXPECT_EQ(nullptr, dict.get());
78 
79   dict.Reset(PyRefType::Owned, PyDict_New());
80   EXPECT_NE(nullptr, dict.get());
81   dict.Reset();
82   EXPECT_EQ(nullptr, dict.get());
83 }
84 
85 TEST_F(PythonDataObjectsTest, TestBorrowedReferences) {
86   PythonInteger long_value(PyRefType::Owned, PyLong_FromLong(3));
87   Py_ssize_t original_refcnt = long_value.get()->ob_refcnt;
88   EXPECT_LE(1, original_refcnt);
89 
90   PythonInteger borrowed_long(PyRefType::Borrowed, long_value.get());
91   EXPECT_EQ(original_refcnt + 1, borrowed_long.get()->ob_refcnt);
92 }
93 
94 TEST_F(PythonDataObjectsTest, TestGlobalNameResolutionNoDot) {
95   PythonObject sys_module = m_main_module.ResolveName("sys");
96   EXPECT_EQ(m_sys_module.get(), sys_module.get());
97   EXPECT_TRUE(sys_module.IsAllocated());
98   EXPECT_TRUE(PythonModule::Check(sys_module.get()));
99 }
100 
101 TEST_F(PythonDataObjectsTest, TestModuleNameResolutionNoDot) {
102   PythonObject sys_path = m_sys_module.ResolveName("path");
103   PythonObject sys_version_info = m_sys_module.ResolveName("version_info");
104   EXPECT_TRUE(sys_path.IsAllocated());
105   EXPECT_TRUE(sys_version_info.IsAllocated());
106 
107   EXPECT_TRUE(PythonList::Check(sys_path.get()));
108 }
109 
110 TEST_F(PythonDataObjectsTest, TestTypeNameResolutionNoDot) {
111   PythonObject sys_version_info = m_sys_module.ResolveName("version_info");
112 
113   PythonObject version_info_type(PyRefType::Owned,
114                                  PyObject_Type(sys_version_info.get()));
115   EXPECT_TRUE(version_info_type.IsAllocated());
116   PythonObject major_version_field = version_info_type.ResolveName("major");
117   EXPECT_TRUE(major_version_field.IsAllocated());
118 }
119 
120 TEST_F(PythonDataObjectsTest, TestInstanceNameResolutionNoDot) {
121   PythonObject sys_version_info = m_sys_module.ResolveName("version_info");
122   PythonObject major_version_field = sys_version_info.ResolveName("major");
123   PythonObject minor_version_field = sys_version_info.ResolveName("minor");
124 
125   EXPECT_TRUE(major_version_field.IsAllocated());
126   EXPECT_TRUE(minor_version_field.IsAllocated());
127 
128   PythonInteger major_version_value =
129       major_version_field.AsType<PythonInteger>();
130   PythonInteger minor_version_value =
131       minor_version_field.AsType<PythonInteger>();
132 
133   EXPECT_EQ(PY_MAJOR_VERSION, major_version_value.GetInteger());
134   EXPECT_EQ(PY_MINOR_VERSION, minor_version_value.GetInteger());
135 }
136 
137 TEST_F(PythonDataObjectsTest, TestGlobalNameResolutionWithDot) {
138   PythonObject sys_path = m_main_module.ResolveName("sys.path");
139   EXPECT_TRUE(sys_path.IsAllocated());
140   EXPECT_TRUE(PythonList::Check(sys_path.get()));
141 
142   PythonInteger version_major =
143       m_main_module.ResolveName("sys.version_info.major")
144           .AsType<PythonInteger>();
145   PythonInteger version_minor =
146       m_main_module.ResolveName("sys.version_info.minor")
147           .AsType<PythonInteger>();
148   EXPECT_TRUE(version_major.IsAllocated());
149   EXPECT_TRUE(version_minor.IsAllocated());
150   EXPECT_EQ(PY_MAJOR_VERSION, version_major.GetInteger());
151   EXPECT_EQ(PY_MINOR_VERSION, version_minor.GetInteger());
152 }
153 
154 TEST_F(PythonDataObjectsTest, TestDictionaryResolutionWithDot) {
155   // Make up a custom dictionary with "sys" pointing to the `sys` module.
156   PythonDictionary dict(PyInitialValue::Empty);
157   dict.SetItemForKey(PythonString("sys"), m_sys_module);
158 
159   // Now use that dictionary to resolve `sys.version_info.major`
160   PythonInteger version_major =
161       PythonObject::ResolveNameWithDictionary("sys.version_info.major", dict)
162           .AsType<PythonInteger>();
163   PythonInteger version_minor =
164       PythonObject::ResolveNameWithDictionary("sys.version_info.minor", dict)
165           .AsType<PythonInteger>();
166   EXPECT_EQ(PY_MAJOR_VERSION, version_major.GetInteger());
167   EXPECT_EQ(PY_MINOR_VERSION, version_minor.GetInteger());
168 }
169 
170 TEST_F(PythonDataObjectsTest, TestPythonInteger) {
171   // Test that integers behave correctly when wrapped by a PythonInteger.
172 
173 #if PY_MAJOR_VERSION < 3
174   // Verify that `PythonInt` works correctly when given a PyInt object.
175   // Note that PyInt doesn't exist in Python 3.x, so this is only for 2.x
176   PyObject *py_int = PyInt_FromLong(12);
177   EXPECT_TRUE(PythonInteger::Check(py_int));
178   PythonInteger python_int(PyRefType::Owned, py_int);
179 
180   EXPECT_EQ(PyObjectType::Integer, python_int.GetObjectType());
181   EXPECT_EQ(12, python_int.GetInteger());
182 #endif
183 
184   // Verify that `PythonInteger` works correctly when given a PyLong object.
185   PyObject *py_long = PyLong_FromLong(12);
186   EXPECT_TRUE(PythonInteger::Check(py_long));
187   PythonInteger python_long(PyRefType::Owned, py_long);
188   EXPECT_EQ(PyObjectType::Integer, python_long.GetObjectType());
189 
190   // Verify that you can reset the value and that it is reflected properly.
191   python_long.SetInteger(40);
192   EXPECT_EQ(40, python_long.GetInteger());
193 
194   // Test that creating a `PythonInteger` object works correctly with the
195   // int constructor.
196   PythonInteger constructed_int(7);
197   EXPECT_EQ(7, constructed_int.GetInteger());
198 }
199 
200 TEST_F(PythonDataObjectsTest, TestPythonBoolean) {
201   // Test PythonBoolean constructed from Py_True
202   EXPECT_TRUE(PythonBoolean::Check(Py_True));
203   PythonBoolean python_true(PyRefType::Owned, Py_True);
204   EXPECT_EQ(PyObjectType::Boolean, python_true.GetObjectType());
205 
206   // Test PythonBoolean constructed from Py_False
207   EXPECT_TRUE(PythonBoolean::Check(Py_False));
208   PythonBoolean python_false(PyRefType::Owned, Py_False);
209   EXPECT_EQ(PyObjectType::Boolean, python_false.GetObjectType());
210 
211   auto test_from_long = [](long value) {
212     PyObject *py_bool = PyBool_FromLong(value);
213     EXPECT_TRUE(PythonBoolean::Check(py_bool));
214     PythonBoolean python_boolean(PyRefType::Owned, py_bool);
215     EXPECT_EQ(PyObjectType::Boolean, python_boolean.GetObjectType());
216     EXPECT_EQ(bool(value), python_boolean.GetValue());
217   };
218 
219   // Test PythonBoolean constructed from long integer values.
220   test_from_long(0); // Test 'false' value.
221   test_from_long(1); // Test 'true' value.
222   test_from_long(~0); // Any value != 0 is 'true'.
223 }
224 
225 TEST_F(PythonDataObjectsTest, TestPythonBytes) {
226   static const char *test_bytes = "PythonDataObjectsTest::TestPythonBytes";
227   PyObject *py_bytes = PyBytes_FromString(test_bytes);
228   EXPECT_TRUE(PythonBytes::Check(py_bytes));
229   PythonBytes python_bytes(PyRefType::Owned, py_bytes);
230 
231 #if PY_MAJOR_VERSION < 3
232   EXPECT_TRUE(PythonString::Check(py_bytes));
233   EXPECT_EQ(PyObjectType::String, python_bytes.GetObjectType());
234 #else
235   EXPECT_FALSE(PythonString::Check(py_bytes));
236   EXPECT_EQ(PyObjectType::Bytes, python_bytes.GetObjectType());
237 #endif
238 
239   llvm::ArrayRef<uint8_t> bytes = python_bytes.GetBytes();
240   EXPECT_EQ(bytes.size(), strlen(test_bytes));
241   EXPECT_EQ(0, ::memcmp(bytes.data(), test_bytes, bytes.size()));
242 }
243 
244 TEST_F(PythonDataObjectsTest, TestPythonByteArray) {
245   static const char *test_bytes = "PythonDataObjectsTest::TestPythonByteArray";
246   llvm::StringRef orig_bytes(test_bytes);
247   PyObject *py_bytes =
248       PyByteArray_FromStringAndSize(test_bytes, orig_bytes.size());
249   EXPECT_TRUE(PythonByteArray::Check(py_bytes));
250   PythonByteArray python_bytes(PyRefType::Owned, py_bytes);
251   EXPECT_EQ(PyObjectType::ByteArray, python_bytes.GetObjectType());
252 
253   llvm::ArrayRef<uint8_t> after_bytes = python_bytes.GetBytes();
254   EXPECT_EQ(after_bytes.size(), orig_bytes.size());
255   EXPECT_EQ(0, ::memcmp(orig_bytes.data(), test_bytes, orig_bytes.size()));
256 }
257 
258 TEST_F(PythonDataObjectsTest, TestPythonString) {
259   // Test that strings behave correctly when wrapped by a PythonString.
260 
261   static const char *test_string = "PythonDataObjectsTest::TestPythonString1";
262   static const char *test_string2 = "PythonDataObjectsTest::TestPythonString2";
263 
264 #if PY_MAJOR_VERSION < 3
265   // Verify that `PythonString` works correctly when given a PyString object.
266   // Note that PyString doesn't exist in Python 3.x, so this is only for 2.x
267   PyObject *py_string = PyString_FromString(test_string);
268   EXPECT_TRUE(PythonString::Check(py_string));
269   PythonString python_string(PyRefType::Owned, py_string);
270 
271   EXPECT_EQ(PyObjectType::String, python_string.GetObjectType());
272   EXPECT_STREQ(test_string, python_string.GetString().data());
273 #else
274   // Verify that `PythonString` works correctly when given a PyUnicode object.
275   PyObject *py_unicode = PyUnicode_FromString(test_string);
276   EXPECT_TRUE(PythonString::Check(py_unicode));
277   PythonString python_unicode(PyRefType::Owned, py_unicode);
278   EXPECT_EQ(PyObjectType::String, python_unicode.GetObjectType());
279   EXPECT_STREQ(test_string, python_unicode.GetString().data());
280 #endif
281 
282   // Test that creating a `PythonString` object works correctly with the
283   // string constructor
284   PythonString constructed_string(test_string2);
285   EXPECT_EQ(test_string2, constructed_string.GetString());
286 }
287 
288 TEST_F(PythonDataObjectsTest, TestPythonStringToStr) {
289   const char *GetString = "PythonDataObjectsTest::TestPythonStringToStr";
290 
291   PythonString str(GetString);
292   EXPECT_EQ(GetString, str.GetString());
293 
294   PythonString str_str = str.Str();
295   EXPECT_EQ(GetString, str_str.GetString());
296 }
297 
298 TEST_F(PythonDataObjectsTest, TestPythonIntegerToStr) {}
299 
300 TEST_F(PythonDataObjectsTest, TestPythonIntegerToStructuredInteger) {
301   PythonInteger integer(7);
302   auto int_sp = integer.CreateStructuredInteger();
303   EXPECT_EQ(7U, int_sp->GetValue());
304 }
305 
306 TEST_F(PythonDataObjectsTest, TestPythonStringToStructuredString) {
307   static const char *test_string =
308       "PythonDataObjectsTest::TestPythonStringToStructuredString";
309   PythonString constructed_string(test_string);
310   auto string_sp = constructed_string.CreateStructuredString();
311   EXPECT_EQ(test_string, string_sp->GetStringValue());
312 }
313 
314 TEST_F(PythonDataObjectsTest, TestPythonListValueEquality) {
315   // Test that a list which is built through the native
316   // Python API behaves correctly when wrapped by a PythonList.
317   static const unsigned list_size = 2;
318   static const long long_value0 = 5;
319   static const char *const string_value1 = "String Index 1";
320 
321   PyObject *py_list = PyList_New(2);
322   EXPECT_TRUE(PythonList::Check(py_list));
323   PythonList list(PyRefType::Owned, py_list);
324 
325   PythonObject list_items[list_size];
326   list_items[0].Reset(PythonInteger(long_value0));
327   list_items[1].Reset(PythonString(string_value1));
328 
329   for (unsigned i = 0; i < list_size; ++i)
330     list.SetItemAtIndex(i, list_items[i]);
331 
332   EXPECT_EQ(list_size, list.GetSize());
333   EXPECT_EQ(PyObjectType::List, list.GetObjectType());
334 
335   // Verify that the values match
336   PythonObject chk_value1 = list.GetItemAtIndex(0);
337   PythonObject chk_value2 = list.GetItemAtIndex(1);
338   EXPECT_TRUE(PythonInteger::Check(chk_value1.get()));
339   EXPECT_TRUE(PythonString::Check(chk_value2.get()));
340 
341   PythonInteger chk_int(PyRefType::Borrowed, chk_value1.get());
342   PythonString chk_str(PyRefType::Borrowed, chk_value2.get());
343 
344   EXPECT_EQ(long_value0, chk_int.GetInteger());
345   EXPECT_EQ(string_value1, chk_str.GetString());
346 }
347 
348 TEST_F(PythonDataObjectsTest, TestPythonListManipulation) {
349   // Test that manipulation of a PythonList behaves correctly when
350   // wrapped by a PythonDictionary.
351 
352   static const long long_value0 = 5;
353   static const char *const string_value1 = "String Index 1";
354 
355   PythonList list(PyInitialValue::Empty);
356   PythonInteger integer(long_value0);
357   PythonString string(string_value1);
358 
359   list.AppendItem(integer);
360   list.AppendItem(string);
361   EXPECT_EQ(2U, list.GetSize());
362 
363   // Verify that the values match
364   PythonObject chk_value1 = list.GetItemAtIndex(0);
365   PythonObject chk_value2 = list.GetItemAtIndex(1);
366   EXPECT_TRUE(PythonInteger::Check(chk_value1.get()));
367   EXPECT_TRUE(PythonString::Check(chk_value2.get()));
368 
369   PythonInteger chk_int(PyRefType::Borrowed, chk_value1.get());
370   PythonString chk_str(PyRefType::Borrowed, chk_value2.get());
371 
372   EXPECT_EQ(long_value0, chk_int.GetInteger());
373   EXPECT_EQ(string_value1, chk_str.GetString());
374 }
375 
376 TEST_F(PythonDataObjectsTest, TestPythonListToStructuredList) {
377   static const long long_value0 = 5;
378   static const char *const string_value1 = "String Index 1";
379 
380   PythonList list(PyInitialValue::Empty);
381   list.AppendItem(PythonInteger(long_value0));
382   list.AppendItem(PythonString(string_value1));
383 
384   auto array_sp = list.CreateStructuredArray();
385   EXPECT_EQ(lldb::eStructuredDataTypeInteger,
386             array_sp->GetItemAtIndex(0)->GetType());
387   EXPECT_EQ(lldb::eStructuredDataTypeString,
388             array_sp->GetItemAtIndex(1)->GetType());
389 
390   auto int_sp = array_sp->GetItemAtIndex(0)->GetAsInteger();
391   auto string_sp = array_sp->GetItemAtIndex(1)->GetAsString();
392 
393   EXPECT_EQ(long_value0, long(int_sp->GetValue()));
394   EXPECT_EQ(string_value1, string_sp->GetValue());
395 }
396 
397 TEST_F(PythonDataObjectsTest, TestPythonTupleSize) {
398   PythonTuple tuple(PyInitialValue::Empty);
399   EXPECT_EQ(0U, tuple.GetSize());
400 
401   tuple = PythonTuple(3);
402   EXPECT_EQ(3U, tuple.GetSize());
403 }
404 
405 TEST_F(PythonDataObjectsTest, TestPythonTupleValues) {
406   PythonTuple tuple(3);
407 
408   PythonInteger int_value(1);
409   PythonString string_value("Test");
410   PythonObject none_value(PyRefType::Borrowed, Py_None);
411 
412   tuple.SetItemAtIndex(0, int_value);
413   tuple.SetItemAtIndex(1, string_value);
414   tuple.SetItemAtIndex(2, none_value);
415 
416   EXPECT_EQ(tuple.GetItemAtIndex(0).get(), int_value.get());
417   EXPECT_EQ(tuple.GetItemAtIndex(1).get(), string_value.get());
418   EXPECT_EQ(tuple.GetItemAtIndex(2).get(), none_value.get());
419 }
420 
421 TEST_F(PythonDataObjectsTest, TestPythonTupleInitializerList) {
422   PythonInteger int_value(1);
423   PythonString string_value("Test");
424   PythonObject none_value(PyRefType::Borrowed, Py_None);
425   PythonTuple tuple{int_value, string_value, none_value};
426   EXPECT_EQ(3U, tuple.GetSize());
427 
428   EXPECT_EQ(tuple.GetItemAtIndex(0).get(), int_value.get());
429   EXPECT_EQ(tuple.GetItemAtIndex(1).get(), string_value.get());
430   EXPECT_EQ(tuple.GetItemAtIndex(2).get(), none_value.get());
431 }
432 
433 TEST_F(PythonDataObjectsTest, TestPythonTupleInitializerList2) {
434   PythonInteger int_value(1);
435   PythonString string_value("Test");
436   PythonObject none_value(PyRefType::Borrowed, Py_None);
437 
438   PythonTuple tuple{int_value.get(), string_value.get(), none_value.get()};
439   EXPECT_EQ(3U, tuple.GetSize());
440 
441   EXPECT_EQ(tuple.GetItemAtIndex(0).get(), int_value.get());
442   EXPECT_EQ(tuple.GetItemAtIndex(1).get(), string_value.get());
443   EXPECT_EQ(tuple.GetItemAtIndex(2).get(), none_value.get());
444 }
445 
446 TEST_F(PythonDataObjectsTest, TestPythonTupleToStructuredList) {
447   PythonInteger int_value(1);
448   PythonString string_value("Test");
449 
450   PythonTuple tuple{int_value.get(), string_value.get()};
451 
452   auto array_sp = tuple.CreateStructuredArray();
453   EXPECT_EQ(tuple.GetSize(), array_sp->GetSize());
454   EXPECT_EQ(lldb::eStructuredDataTypeInteger,
455             array_sp->GetItemAtIndex(0)->GetType());
456   EXPECT_EQ(lldb::eStructuredDataTypeString,
457             array_sp->GetItemAtIndex(1)->GetType());
458 }
459 
460 TEST_F(PythonDataObjectsTest, TestPythonDictionaryValueEquality) {
461   // Test that a dictionary which is built through the native
462   // Python API behaves correctly when wrapped by a PythonDictionary.
463   static const unsigned dict_entries = 2;
464   const char *key_0 = "Key 0";
465   int key_1 = 1;
466   const int value_0 = 0;
467   const char *value_1 = "Value 1";
468 
469   PythonObject py_keys[dict_entries];
470   PythonObject py_values[dict_entries];
471 
472   py_keys[0].Reset(PythonString(key_0));
473   py_keys[1].Reset(PythonInteger(key_1));
474   py_values[0].Reset(PythonInteger(value_0));
475   py_values[1].Reset(PythonString(value_1));
476 
477   PyObject *py_dict = PyDict_New();
478   EXPECT_TRUE(PythonDictionary::Check(py_dict));
479   PythonDictionary dict(PyRefType::Owned, py_dict);
480 
481   for (unsigned i = 0; i < dict_entries; ++i)
482     PyDict_SetItem(py_dict, py_keys[i].get(), py_values[i].get());
483   EXPECT_EQ(dict.GetSize(), dict_entries);
484   EXPECT_EQ(PyObjectType::Dictionary, dict.GetObjectType());
485 
486   // Verify that the values match
487   PythonObject chk_value1 = dict.GetItemForKey(py_keys[0]);
488   PythonObject chk_value2 = dict.GetItemForKey(py_keys[1]);
489   EXPECT_TRUE(PythonInteger::Check(chk_value1.get()));
490   EXPECT_TRUE(PythonString::Check(chk_value2.get()));
491 
492   PythonInteger chk_int(PyRefType::Borrowed, chk_value1.get());
493   PythonString chk_str(PyRefType::Borrowed, chk_value2.get());
494 
495   EXPECT_EQ(value_0, chk_int.GetInteger());
496   EXPECT_EQ(value_1, chk_str.GetString());
497 }
498 
499 TEST_F(PythonDataObjectsTest, TestPythonDictionaryManipulation) {
500   // Test that manipulation of a dictionary behaves correctly when wrapped
501   // by a PythonDictionary.
502   static const unsigned dict_entries = 2;
503 
504   const char *const key_0 = "Key 0";
505   const char *const key_1 = "Key 1";
506   const long value_0 = 1;
507   const char *const value_1 = "Value 1";
508 
509   PythonString keys[dict_entries];
510   PythonObject values[dict_entries];
511 
512   keys[0].Reset(PythonString(key_0));
513   keys[1].Reset(PythonString(key_1));
514   values[0].Reset(PythonInteger(value_0));
515   values[1].Reset(PythonString(value_1));
516 
517   PythonDictionary dict(PyInitialValue::Empty);
518   for (int i = 0; i < 2; ++i)
519     dict.SetItemForKey(keys[i], values[i]);
520 
521   EXPECT_EQ(dict_entries, dict.GetSize());
522 
523   // Verify that the keys and values match
524   PythonObject chk_value1 = dict.GetItemForKey(keys[0]);
525   PythonObject chk_value2 = dict.GetItemForKey(keys[1]);
526   EXPECT_TRUE(PythonInteger::Check(chk_value1.get()));
527   EXPECT_TRUE(PythonString::Check(chk_value2.get()));
528 
529   PythonInteger chk_int(PyRefType::Borrowed, chk_value1.get());
530   PythonString chk_str(PyRefType::Borrowed, chk_value2.get());
531 
532   EXPECT_EQ(value_0, chk_int.GetInteger());
533   EXPECT_EQ(value_1, chk_str.GetString());
534 }
535 
536 TEST_F(PythonDataObjectsTest, TestPythonDictionaryToStructuredDictionary) {
537   static const char *const string_key0 = "String Key 0";
538   static const char *const string_key1 = "String Key 1";
539 
540   static const char *const string_value0 = "String Value 0";
541   static const long int_value1 = 7;
542 
543   PythonDictionary dict(PyInitialValue::Empty);
544   dict.SetItemForKey(PythonString(string_key0), PythonString(string_value0));
545   dict.SetItemForKey(PythonString(string_key1), PythonInteger(int_value1));
546 
547   auto dict_sp = dict.CreateStructuredDictionary();
548   EXPECT_EQ(2U, dict_sp->GetSize());
549 
550   EXPECT_TRUE(dict_sp->HasKey(string_key0));
551   EXPECT_TRUE(dict_sp->HasKey(string_key1));
552 
553   auto string_sp = dict_sp->GetValueForKey(string_key0)->GetAsString();
554   auto int_sp = dict_sp->GetValueForKey(string_key1)->GetAsInteger();
555 
556   EXPECT_EQ(string_value0, string_sp->GetValue());
557   EXPECT_EQ(int_value1, long(int_sp->GetValue()));
558 }
559 
560 TEST_F(PythonDataObjectsTest, TestPythonCallableCheck) {
561   PythonObject sys_exc_info = m_sys_module.ResolveName("exc_info");
562   PythonObject none(PyRefType::Borrowed, Py_None);
563 
564   EXPECT_TRUE(PythonCallable::Check(sys_exc_info.get()));
565   EXPECT_FALSE(PythonCallable::Check(none.get()));
566 }
567 
568 TEST_F(PythonDataObjectsTest, TestPythonCallableInvoke) {
569   auto list = m_builtins_module.ResolveName("list").AsType<PythonCallable>();
570   PythonInteger one(1);
571   PythonString two("two");
572   PythonTuple three = {one, two};
573 
574   PythonTuple tuple_to_convert = {one, two, three};
575   PythonObject result = list({tuple_to_convert});
576 
577   EXPECT_TRUE(PythonList::Check(result.get()));
578   auto list_result = result.AsType<PythonList>();
579   EXPECT_EQ(3U, list_result.GetSize());
580   EXPECT_EQ(one.get(), list_result.GetItemAtIndex(0).get());
581   EXPECT_EQ(two.get(), list_result.GetItemAtIndex(1).get());
582   EXPECT_EQ(three.get(), list_result.GetItemAtIndex(2).get());
583 }
584 
585 TEST_F(PythonDataObjectsTest, TestPythonFile) {
586   auto file = FileSystem::Instance().Open(FileSpec(FileSystem::DEV_NULL),
587                                           File::eOpenOptionRead);
588   ASSERT_THAT_EXPECTED(file, llvm::Succeeded());
589   auto py_file = PythonFile::FromFile(*file.get(), "r");
590   ASSERT_THAT_EXPECTED(py_file, llvm::Succeeded());
591   EXPECT_TRUE(PythonFile::Check(py_file.get().get()));
592 }
593 
594 TEST_F(PythonDataObjectsTest, TestObjectAttributes) {
595   PythonInteger py_int(42);
596   EXPECT_TRUE(py_int.HasAttribute("numerator"));
597   EXPECT_FALSE(py_int.HasAttribute("this_should_not_exist"));
598 
599   PythonInteger numerator_attr =
600       py_int.GetAttributeValue("numerator").AsType<PythonInteger>();
601   EXPECT_TRUE(numerator_attr.IsAllocated());
602   EXPECT_EQ(42, numerator_attr.GetInteger());
603 }
604 
605 TEST_F(PythonDataObjectsTest, TestExtractingUInt64ThroughStructuredData) {
606   // Make up a custom dictionary with "sys" pointing to the `sys` module.
607   const char *key_name = "addr";
608   const uint64_t value = 0xf000000000000000ull;
609   PythonDictionary python_dict(PyInitialValue::Empty);
610   PythonInteger python_ull_value(PyRefType::Owned,
611                                  PyLong_FromUnsignedLongLong(value));
612   python_dict.SetItemForKey(PythonString(key_name), python_ull_value);
613   StructuredData::ObjectSP structured_data_sp =
614       python_dict.CreateStructuredObject();
615   EXPECT_TRUE((bool)structured_data_sp);
616   if (structured_data_sp) {
617     StructuredData::Dictionary *structured_dict_ptr =
618         structured_data_sp->GetAsDictionary();
619     EXPECT_TRUE(structured_dict_ptr != nullptr);
620     if (structured_dict_ptr) {
621       StructuredData::ObjectSP structured_addr_value_sp =
622           structured_dict_ptr->GetValueForKey(key_name);
623       EXPECT_TRUE((bool)structured_addr_value_sp);
624       const uint64_t extracted_value =
625           structured_addr_value_sp->GetIntegerValue(123);
626       EXPECT_TRUE(extracted_value == value);
627     }
628   }
629 }
630 
631 TEST_F(PythonDataObjectsTest, TestCallable) {
632 
633   PythonDictionary globals(PyInitialValue::Empty);
634   auto builtins = PythonModule::BuiltinsModule();
635   llvm::Error error = globals.SetItem("__builtins__", builtins);
636   ASSERT_FALSE(error);
637 
638   {
639     PyObject *o = PyRun_String("lambda x : x", Py_eval_input, globals.get(),
640                                globals.get());
641     ASSERT_FALSE(o == NULL);
642     auto lambda = Take<PythonCallable>(o);
643     auto arginfo = lambda.GetArgInfo();
644     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
645     EXPECT_EQ(arginfo.get().count, 1);
646     EXPECT_EQ(arginfo.get().has_varargs, false);
647     EXPECT_EQ(arginfo.get().is_bound_method, false);
648   }
649 
650   {
651     PyObject *o = PyRun_String("lambda x,y=0: x", Py_eval_input, globals.get(),
652                                globals.get());
653     ASSERT_FALSE(o == NULL);
654     auto lambda = Take<PythonCallable>(o);
655     auto arginfo = lambda.GetArgInfo();
656     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
657     EXPECT_EQ(arginfo.get().count, 2);
658     EXPECT_EQ(arginfo.get().has_varargs, false);
659     EXPECT_EQ(arginfo.get().is_bound_method, false);
660   }
661 
662   {
663     PyObject *o = PyRun_String("lambda x,y=0, **kw: x", Py_eval_input,
664                                globals.get(), globals.get());
665     ASSERT_FALSE(o == NULL);
666     auto lambda = Take<PythonCallable>(o);
667     auto arginfo = lambda.GetArgInfo();
668     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
669     EXPECT_EQ(arginfo.get().count, 2);
670     EXPECT_EQ(arginfo.get().has_varargs, false);
671   }
672 
673   {
674     PyObject *o = PyRun_String("lambda x,y,*a: x", Py_eval_input, globals.get(),
675                                globals.get());
676     ASSERT_FALSE(o == NULL);
677     auto lambda = Take<PythonCallable>(o);
678     auto arginfo = lambda.GetArgInfo();
679     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
680     EXPECT_EQ(arginfo.get().count, 2);
681     EXPECT_EQ(arginfo.get().has_varargs, true);
682     EXPECT_EQ(arginfo.get().is_bound_method, false);
683   }
684 
685   {
686     PyObject *o = PyRun_String("lambda x,y,*a,**kw: x", Py_eval_input,
687                                globals.get(), globals.get());
688     ASSERT_FALSE(o == NULL);
689     auto lambda = Take<PythonCallable>(o);
690     auto arginfo = lambda.GetArgInfo();
691     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
692     EXPECT_EQ(arginfo.get().count, 2);
693     EXPECT_EQ(arginfo.get().has_varargs, true);
694   }
695 
696   {
697     const char *script = R"(
698 class Foo:
699   def bar(self, x):
700      return x
701 bar_bound   = Foo().bar
702 bar_unbound = Foo.bar
703 )";
704     PyObject *o =
705         PyRun_String(script, Py_file_input, globals.get(), globals.get());
706     ASSERT_FALSE(o == NULL);
707     Take<PythonObject>(o);
708 
709     auto bar_bound = As<PythonCallable>(globals.GetItem("bar_bound"));
710     ASSERT_THAT_EXPECTED(bar_bound, llvm::Succeeded());
711     auto arginfo = bar_bound.get().GetArgInfo();
712     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
713     EXPECT_EQ(arginfo.get().count, 2); // FIXME, wrong
714     EXPECT_EQ(arginfo.get().has_varargs, false);
715     EXPECT_EQ(arginfo.get().is_bound_method, true);
716 
717     auto bar_unbound = As<PythonCallable>(globals.GetItem("bar_unbound"));
718     ASSERT_THAT_EXPECTED(bar_unbound, llvm::Succeeded());
719     arginfo = bar_unbound.get().GetArgInfo();
720     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
721     EXPECT_EQ(arginfo.get().count, 2);
722     EXPECT_EQ(arginfo.get().has_varargs, false);
723     EXPECT_EQ(arginfo.get().is_bound_method, false);
724   }
725 
726 #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
727 
728   // the old implementation of GetArgInfo just doesn't work on builtins.
729 
730   {
731     auto builtins = PythonModule::BuiltinsModule();
732     auto hex = As<PythonCallable>(builtins.GetAttribute("hex"));
733     ASSERT_THAT_EXPECTED(hex, llvm::Succeeded());
734     auto arginfo = hex.get().GetArgInfo();
735     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
736     EXPECT_EQ(arginfo.get().count, 1);
737     EXPECT_EQ(arginfo.get().has_varargs, false);
738     EXPECT_EQ(arginfo.get().is_bound_method, false);
739   }
740 
741 #endif
742 }