xref: /llvm-project/lldb/unittests/ScriptInterpreter/Python/PythonDataObjectsTests.cpp (revision 27f2908fbc8092f3567385a63676d623523b318b)
1 //===-- PythonDataObjectsTests.cpp ----------------------------------------===//
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 #include <variant>
23 
24 using namespace lldb_private;
25 using namespace lldb_private::python;
26 using llvm::Expected;
27 
28 class PythonDataObjectsTest : public PythonTestSuite {
29 public:
30   void SetUp() override {
31     PythonTestSuite::SetUp();
32 
33     m_sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
34     m_main_module = PythonModule::MainModule();
35     m_builtins_module = PythonModule::BuiltinsModule();
36   }
37 
38   void TearDown() override {
39     m_sys_module.Reset();
40     m_main_module.Reset();
41     m_builtins_module.Reset();
42 
43     PythonTestSuite::TearDown();
44   }
45 
46 protected:
47   PythonModule m_sys_module;
48   PythonModule m_main_module;
49   PythonModule m_builtins_module;
50 };
51 
52 TEST_F(PythonDataObjectsTest, TestOwnedReferences) {
53   // After creating a new object, the refcount should be >= 1
54   PyObject *obj = PyBytes_FromString("foo");
55   Py_ssize_t original_refcnt = Py_REFCNT(obj);
56   EXPECT_LE(1, original_refcnt);
57 
58   // If we take an owned reference, the refcount should be the same
59   PythonObject owned(PyRefType::Owned, obj);
60   Py_ssize_t owned_refcnt = Py_REFCNT(owned.get());
61   EXPECT_EQ(original_refcnt, owned_refcnt);
62 
63   // Take another reference and verify that the refcount increases by 1
64   PythonObject strong_ref(owned);
65   Py_ssize_t strong_refcnt = Py_REFCNT(strong_ref.get());
66   EXPECT_EQ(original_refcnt + 1, strong_refcnt);
67 
68   // If we reset the first one, the refcount should be the original value.
69   owned.Reset();
70   strong_refcnt = Py_REFCNT(strong_ref.get());
71   EXPECT_EQ(original_refcnt, strong_refcnt);
72 }
73 
74 TEST_F(PythonDataObjectsTest, TestResetting) {
75   PythonDictionary dict(PyInitialValue::Empty);
76 
77   PyObject *new_dict = PyDict_New();
78   dict = Take<PythonDictionary>(new_dict);
79   EXPECT_EQ(new_dict, dict.get());
80 
81   dict = Take<PythonDictionary>(PyDict_New());
82   EXPECT_NE(nullptr, dict.get());
83   dict.Reset();
84   EXPECT_EQ(nullptr, dict.get());
85 }
86 
87 TEST_F(PythonDataObjectsTest, TestBorrowedReferences) {
88   PythonByteArray byte_value(PyRefType::Owned,
89                              PyByteArray_FromStringAndSize("foo", 3));
90   Py_ssize_t original_refcnt = Py_REFCNT(byte_value.get());
91   EXPECT_LE(1, original_refcnt);
92 
93   PythonByteArray borrowed_byte(PyRefType::Borrowed, byte_value.get());
94   Py_ssize_t borrowed_refcnt = Py_REFCNT(borrowed_byte.get());
95 
96   EXPECT_EQ(original_refcnt + 1, borrowed_refcnt);
97 }
98 
99 TEST_F(PythonDataObjectsTest, TestGlobalNameResolutionNoDot) {
100   PythonObject sys_module = m_main_module.ResolveName("sys");
101   EXPECT_EQ(m_sys_module.get(), sys_module.get());
102   EXPECT_TRUE(sys_module.IsAllocated());
103   EXPECT_TRUE(PythonModule::Check(sys_module.get()));
104 }
105 
106 TEST_F(PythonDataObjectsTest, TestModuleNameResolutionNoDot) {
107   PythonObject sys_path = m_sys_module.ResolveName("path");
108   PythonObject sys_version_info = m_sys_module.ResolveName("version_info");
109   EXPECT_TRUE(sys_path.IsAllocated());
110   EXPECT_TRUE(sys_version_info.IsAllocated());
111 
112   EXPECT_TRUE(PythonList::Check(sys_path.get()));
113 }
114 
115 TEST_F(PythonDataObjectsTest, TestTypeNameResolutionNoDot) {
116   PythonObject sys_version_info = m_sys_module.ResolveName("version_info");
117 
118   PythonObject version_info_type(PyRefType::Owned,
119                                  PyObject_Type(sys_version_info.get()));
120   EXPECT_TRUE(version_info_type.IsAllocated());
121   PythonObject major_version_field = version_info_type.ResolveName("major");
122   EXPECT_TRUE(major_version_field.IsAllocated());
123 }
124 
125 TEST_F(PythonDataObjectsTest, TestInstanceNameResolutionNoDot) {
126   PythonObject sys_version_info = m_sys_module.ResolveName("version_info");
127   PythonObject major_version_field = sys_version_info.ResolveName("major");
128   PythonObject minor_version_field = sys_version_info.ResolveName("minor");
129 
130   EXPECT_TRUE(major_version_field.IsAllocated());
131   EXPECT_TRUE(minor_version_field.IsAllocated());
132 
133   auto major_version_value = As<long long>(major_version_field);
134   auto minor_version_value = As<long long>(minor_version_field);
135 
136   EXPECT_THAT_EXPECTED(major_version_value, llvm::HasValue(PY_MAJOR_VERSION));
137   EXPECT_THAT_EXPECTED(minor_version_value, llvm::HasValue(PY_MINOR_VERSION));
138 }
139 
140 TEST_F(PythonDataObjectsTest, TestGlobalNameResolutionWithDot) {
141   PythonObject sys_path = m_main_module.ResolveName("sys.path");
142   EXPECT_TRUE(sys_path.IsAllocated());
143   EXPECT_TRUE(PythonList::Check(sys_path.get()));
144 
145   auto version_major =
146       As<long long>(m_main_module.ResolveName("sys.version_info.major"));
147 
148   auto version_minor =
149       As<long long>(m_main_module.ResolveName("sys.version_info.minor"));
150 
151   EXPECT_THAT_EXPECTED(version_major, llvm::HasValue(PY_MAJOR_VERSION));
152   EXPECT_THAT_EXPECTED(version_minor, llvm::HasValue(PY_MINOR_VERSION));
153 }
154 
155 TEST_F(PythonDataObjectsTest, TestDictionaryResolutionWithDot) {
156   // Make up a custom dictionary with "sys" pointing to the `sys` module.
157   PythonDictionary dict(PyInitialValue::Empty);
158   dict.SetItemForKey(PythonString("sys"), m_sys_module);
159 
160   // Now use that dictionary to resolve `sys.version_info.major`
161   auto version_major = As<long long>(
162       PythonObject::ResolveNameWithDictionary("sys.version_info.major", dict));
163 
164   auto version_minor = As<long long>(
165       PythonObject::ResolveNameWithDictionary("sys.version_info.minor", dict));
166 
167   EXPECT_THAT_EXPECTED(version_major, llvm::HasValue(PY_MAJOR_VERSION));
168   EXPECT_THAT_EXPECTED(version_minor, llvm::HasValue(PY_MINOR_VERSION));
169 }
170 
171 TEST_F(PythonDataObjectsTest, TestPythonInteger) {
172   // Test that integers behave correctly when wrapped by a PythonInteger.
173 
174   // Verify that `PythonInteger` works correctly when given a PyLong object.
175   PyObject *py_long = PyLong_FromLong(12);
176   EXPECT_TRUE(PythonInteger::Check(py_long));
177   PythonInteger python_long(PyRefType::Owned, py_long);
178   EXPECT_EQ(PyObjectType::Integer, python_long.GetObjectType());
179 
180   // Verify that you can reset the value and that it is reflected properly.
181   python_long.SetInteger(40);
182   auto e = As<long long>(python_long);
183   EXPECT_THAT_EXPECTED(e, llvm::HasValue(40));
184 
185   // Test that creating a `PythonInteger` object works correctly with the
186   // int constructor.
187   PythonInteger constructed_int(7);
188   auto value = As<long long>(constructed_int);
189   EXPECT_THAT_EXPECTED(value, llvm::HasValue(7));
190 }
191 
192 TEST_F(PythonDataObjectsTest, TestPythonBoolean) {
193   // Test PythonBoolean constructed from Py_True
194   EXPECT_TRUE(PythonBoolean::Check(Py_True));
195   PythonBoolean python_true(PyRefType::Owned, Py_True);
196   EXPECT_EQ(PyObjectType::Boolean, python_true.GetObjectType());
197 
198   // Test PythonBoolean constructed from Py_False
199   EXPECT_TRUE(PythonBoolean::Check(Py_False));
200   PythonBoolean python_false(PyRefType::Owned, Py_False);
201   EXPECT_EQ(PyObjectType::Boolean, python_false.GetObjectType());
202 
203   auto test_from_long = [](long value) {
204     PyObject *py_bool = PyBool_FromLong(value);
205     EXPECT_TRUE(PythonBoolean::Check(py_bool));
206     PythonBoolean python_boolean(PyRefType::Owned, py_bool);
207     EXPECT_EQ(PyObjectType::Boolean, python_boolean.GetObjectType());
208     EXPECT_EQ(bool(value), python_boolean.GetValue());
209   };
210 
211   // Test PythonBoolean constructed from long integer values.
212   test_from_long(0); // Test 'false' value.
213   test_from_long(1); // Test 'true' value.
214   test_from_long(~0); // Any value != 0 is 'true'.
215 }
216 
217 TEST_F(PythonDataObjectsTest, TestPythonBytes) {
218   static const char *test_bytes = "PythonDataObjectsTest::TestPythonBytes";
219   PyObject *py_bytes = PyBytes_FromString(test_bytes);
220   EXPECT_TRUE(PythonBytes::Check(py_bytes));
221   PythonBytes python_bytes(PyRefType::Owned, py_bytes);
222 
223   EXPECT_FALSE(PythonString::Check(py_bytes));
224   EXPECT_EQ(PyObjectType::Bytes, python_bytes.GetObjectType());
225 
226   llvm::ArrayRef<uint8_t> bytes = python_bytes.GetBytes();
227   EXPECT_EQ(bytes.size(), strlen(test_bytes));
228   EXPECT_EQ(0, ::memcmp(bytes.data(), test_bytes, bytes.size()));
229 }
230 
231 TEST_F(PythonDataObjectsTest, TestPythonByteArray) {
232   static const char *test_bytes = "PythonDataObjectsTest::TestPythonByteArray";
233   llvm::StringRef orig_bytes(test_bytes);
234   PyObject *py_bytes =
235       PyByteArray_FromStringAndSize(test_bytes, orig_bytes.size());
236   EXPECT_TRUE(PythonByteArray::Check(py_bytes));
237   PythonByteArray python_bytes(PyRefType::Owned, py_bytes);
238   EXPECT_EQ(PyObjectType::ByteArray, python_bytes.GetObjectType());
239 
240   llvm::ArrayRef<uint8_t> after_bytes = python_bytes.GetBytes();
241   EXPECT_EQ(after_bytes.size(), orig_bytes.size());
242   EXPECT_EQ(0, ::memcmp(orig_bytes.data(), test_bytes, orig_bytes.size()));
243 }
244 
245 TEST_F(PythonDataObjectsTest, TestPythonString) {
246   // Test that strings behave correctly when wrapped by a PythonString.
247 
248   static const char *test_string = "PythonDataObjectsTest::TestPythonString1";
249   static const char *test_string2 = "PythonDataObjectsTest::TestPythonString2";
250 
251   // Verify that `PythonString` works correctly when given a PyUnicode object.
252   PyObject *py_unicode = PyUnicode_FromString(test_string);
253   EXPECT_TRUE(PythonString::Check(py_unicode));
254   PythonString python_unicode(PyRefType::Owned, py_unicode);
255   EXPECT_EQ(PyObjectType::String, python_unicode.GetObjectType());
256   EXPECT_STREQ(test_string, python_unicode.GetString().data());
257 
258   // Test that creating a `PythonString` object works correctly with the
259   // string constructor
260   PythonString constructed_string(test_string2);
261   EXPECT_EQ(test_string2, constructed_string.GetString());
262 }
263 
264 TEST_F(PythonDataObjectsTest, TestPythonStringToStr) {
265   const char *GetString = "PythonDataObjectsTest::TestPythonStringToStr";
266 
267   PythonString str(GetString);
268   EXPECT_EQ(GetString, str.GetString());
269 
270   PythonString str_str = str.Str();
271   EXPECT_EQ(GetString, str_str.GetString());
272 }
273 
274 TEST_F(PythonDataObjectsTest, TestPythonIntegerToStr) {}
275 
276 TEST_F(PythonDataObjectsTest, TestPythonIntegerToStructuredUnsignedInteger) {
277   PythonInteger integer(7);
278   auto int_sp = integer.CreateStructuredInteger();
279   EXPECT_TRUE(
280       std::holds_alternative<StructuredData::UnsignedIntegerSP>(int_sp));
281   StructuredData::UnsignedIntegerSP uint_sp =
282       std::get<StructuredData::UnsignedIntegerSP>(int_sp);
283   EXPECT_EQ(7U, uint_sp->GetValue());
284 }
285 
286 TEST_F(PythonDataObjectsTest, TestPythonIntegerToStructuredSignedInteger) {
287   PythonInteger integer(-42);
288   auto int_sp = integer.CreateStructuredInteger();
289   EXPECT_TRUE(std::holds_alternative<StructuredData::SignedIntegerSP>(int_sp));
290   StructuredData::SignedIntegerSP sint_sp =
291       std::get<StructuredData::SignedIntegerSP>(int_sp);
292   EXPECT_EQ(-42, sint_sp->GetValue());
293 }
294 
295 TEST_F(PythonDataObjectsTest, TestPythonStringToStructuredString) {
296   static const char *test_string =
297       "PythonDataObjectsTest::TestPythonStringToStructuredString";
298   PythonString constructed_string(test_string);
299   auto string_sp = constructed_string.CreateStructuredString();
300   EXPECT_EQ(test_string, string_sp->GetStringValue());
301 }
302 
303 TEST_F(PythonDataObjectsTest, TestPythonListValueEquality) {
304   // Test that a list which is built through the native
305   // Python API behaves correctly when wrapped by a PythonList.
306   static const unsigned list_size = 2;
307   static const long long_value0 = 5;
308   static const char *const string_value1 = "String Index 1";
309 
310   PyObject *py_list = PyList_New(2);
311   EXPECT_TRUE(PythonList::Check(py_list));
312   PythonList list(PyRefType::Owned, py_list);
313 
314   PythonObject list_items[list_size];
315   list_items[0] = PythonInteger(long_value0);
316   list_items[1] = PythonString(string_value1);
317 
318   for (unsigned i = 0; i < list_size; ++i)
319     list.SetItemAtIndex(i, list_items[i]);
320 
321   EXPECT_EQ(list_size, list.GetSize());
322   EXPECT_EQ(PyObjectType::List, list.GetObjectType());
323 
324   // Verify that the values match
325   PythonObject chk_value1 = list.GetItemAtIndex(0);
326   PythonObject chk_value2 = list.GetItemAtIndex(1);
327   EXPECT_TRUE(PythonInteger::Check(chk_value1.get()));
328   EXPECT_TRUE(PythonString::Check(chk_value2.get()));
329 
330   PythonInteger chk_int(PyRefType::Borrowed, chk_value1.get());
331   PythonString chk_str(PyRefType::Borrowed, chk_value2.get());
332 
333   auto chkint = As<long long>(chk_value1);
334   ASSERT_THAT_EXPECTED(chkint, llvm::HasValue(long_value0));
335   EXPECT_EQ(string_value1, chk_str.GetString());
336 }
337 
338 TEST_F(PythonDataObjectsTest, TestPythonListManipulation) {
339   // Test that manipulation of a PythonList behaves correctly when
340   // wrapped by a PythonDictionary.
341 
342   static const long long_value0 = 5;
343   static const char *const string_value1 = "String Index 1";
344 
345   PythonList list(PyInitialValue::Empty);
346   PythonInteger integer(long_value0);
347   PythonString string(string_value1);
348 
349   list.AppendItem(integer);
350   list.AppendItem(string);
351   EXPECT_EQ(2U, list.GetSize());
352 
353   // Verify that the values match
354   PythonObject chk_value1 = list.GetItemAtIndex(0);
355   PythonObject chk_value2 = list.GetItemAtIndex(1);
356   EXPECT_TRUE(PythonInteger::Check(chk_value1.get()));
357   EXPECT_TRUE(PythonString::Check(chk_value2.get()));
358 
359   PythonInteger chk_int(PyRefType::Borrowed, chk_value1.get());
360   PythonString chk_str(PyRefType::Borrowed, chk_value2.get());
361 
362   auto e = As<long long>(chk_int);
363   EXPECT_THAT_EXPECTED(e, llvm::HasValue(long_value0));
364   EXPECT_EQ(string_value1, chk_str.GetString());
365 }
366 
367 TEST_F(PythonDataObjectsTest, TestPythonListToStructuredList) {
368   static const long long_value0 = 5;
369   static const char *const string_value1 = "String Index 1";
370 
371   PythonList list(PyInitialValue::Empty);
372   list.AppendItem(PythonInteger(long_value0));
373   list.AppendItem(PythonString(string_value1));
374 
375   auto array_sp = list.CreateStructuredArray();
376   EXPECT_EQ(lldb::eStructuredDataTypeInteger,
377             array_sp->GetItemAtIndex(0)->GetType());
378   EXPECT_EQ(lldb::eStructuredDataTypeString,
379             array_sp->GetItemAtIndex(1)->GetType());
380 
381   auto int_sp = array_sp->GetItemAtIndex(0)->GetAsUnsignedInteger();
382   auto string_sp = array_sp->GetItemAtIndex(1)->GetAsString();
383 
384   EXPECT_EQ(long_value0, long(int_sp->GetValue()));
385   EXPECT_EQ(string_value1, string_sp->GetValue());
386 }
387 
388 TEST_F(PythonDataObjectsTest, TestPythonTupleSize) {
389   PythonTuple tuple(PyInitialValue::Empty);
390   EXPECT_EQ(0U, tuple.GetSize());
391 
392   tuple = PythonTuple(3);
393   EXPECT_EQ(3U, tuple.GetSize());
394 }
395 
396 TEST_F(PythonDataObjectsTest, TestPythonTupleValues) {
397   PythonTuple tuple(3);
398 
399   PythonInteger int_value(1);
400   PythonString string_value("Test");
401   PythonObject none_value(PyRefType::Borrowed, Py_None);
402 
403   tuple.SetItemAtIndex(0, int_value);
404   tuple.SetItemAtIndex(1, string_value);
405   tuple.SetItemAtIndex(2, none_value);
406 
407   EXPECT_EQ(tuple.GetItemAtIndex(0).get(), int_value.get());
408   EXPECT_EQ(tuple.GetItemAtIndex(1).get(), string_value.get());
409   EXPECT_EQ(tuple.GetItemAtIndex(2).get(), none_value.get());
410 }
411 
412 TEST_F(PythonDataObjectsTest, TestPythonTupleInitializerList) {
413   PythonInteger int_value(1);
414   PythonString string_value("Test");
415   PythonObject none_value(PyRefType::Borrowed, Py_None);
416   PythonTuple tuple{int_value, string_value, none_value};
417   EXPECT_EQ(3U, tuple.GetSize());
418 
419   EXPECT_EQ(tuple.GetItemAtIndex(0).get(), int_value.get());
420   EXPECT_EQ(tuple.GetItemAtIndex(1).get(), string_value.get());
421   EXPECT_EQ(tuple.GetItemAtIndex(2).get(), none_value.get());
422 }
423 
424 TEST_F(PythonDataObjectsTest, TestPythonTupleInitializerList2) {
425   PythonInteger int_value(1);
426   PythonString string_value("Test");
427   PythonObject none_value(PyRefType::Borrowed, Py_None);
428 
429   PythonTuple tuple{int_value.get(), string_value.get(), none_value.get()};
430   EXPECT_EQ(3U, tuple.GetSize());
431 
432   EXPECT_EQ(tuple.GetItemAtIndex(0).get(), int_value.get());
433   EXPECT_EQ(tuple.GetItemAtIndex(1).get(), string_value.get());
434   EXPECT_EQ(tuple.GetItemAtIndex(2).get(), none_value.get());
435 }
436 
437 TEST_F(PythonDataObjectsTest, TestPythonTupleToStructuredList) {
438   PythonInteger int_value(1);
439   PythonString string_value("Test");
440 
441   PythonTuple tuple{int_value.get(), string_value.get()};
442 
443   auto array_sp = tuple.CreateStructuredArray();
444   EXPECT_EQ(tuple.GetSize(), array_sp->GetSize());
445   EXPECT_EQ(lldb::eStructuredDataTypeInteger,
446             array_sp->GetItemAtIndex(0)->GetType());
447   EXPECT_EQ(lldb::eStructuredDataTypeString,
448             array_sp->GetItemAtIndex(1)->GetType());
449 }
450 
451 TEST_F(PythonDataObjectsTest, TestPythonDictionaryValueEquality) {
452   // Test that a dictionary which is built through the native
453   // Python API behaves correctly when wrapped by a PythonDictionary.
454   static const unsigned dict_entries = 2;
455   const char *key_0 = "Key 0";
456   int key_1 = 1;
457   const int value_0 = 0;
458   const char *value_1 = "Value 1";
459 
460   PythonObject py_keys[dict_entries];
461   PythonObject py_values[dict_entries];
462 
463   py_keys[0] = PythonString(key_0);
464   py_keys[1] = PythonInteger(key_1);
465   py_values[0] = PythonInteger(value_0);
466   py_values[1] = PythonString(value_1);
467 
468   PyObject *py_dict = PyDict_New();
469   EXPECT_TRUE(PythonDictionary::Check(py_dict));
470   PythonDictionary dict(PyRefType::Owned, py_dict);
471 
472   for (unsigned i = 0; i < dict_entries; ++i)
473     PyDict_SetItem(py_dict, py_keys[i].get(), py_values[i].get());
474   EXPECT_EQ(dict.GetSize(), dict_entries);
475   EXPECT_EQ(PyObjectType::Dictionary, dict.GetObjectType());
476 
477   // Verify that the values match
478   PythonObject chk_value1 = dict.GetItemForKey(py_keys[0]);
479   PythonObject chk_value2 = dict.GetItemForKey(py_keys[1]);
480   EXPECT_TRUE(PythonInteger::Check(chk_value1.get()));
481   EXPECT_TRUE(PythonString::Check(chk_value2.get()));
482 
483   PythonString chk_str(PyRefType::Borrowed, chk_value2.get());
484   auto chkint = As<long long>(chk_value1);
485 
486   EXPECT_THAT_EXPECTED(chkint, llvm::HasValue(value_0));
487   EXPECT_EQ(value_1, chk_str.GetString());
488 }
489 
490 TEST_F(PythonDataObjectsTest, TestPythonDictionaryManipulation) {
491   // Test that manipulation of a dictionary behaves correctly when wrapped
492   // by a PythonDictionary.
493   static const unsigned dict_entries = 2;
494 
495   const char *const key_0 = "Key 0";
496   const char *const key_1 = "Key 1";
497   const long value_0 = 1;
498   const char *const value_1 = "Value 1";
499 
500   PythonString keys[dict_entries];
501   PythonObject values[dict_entries];
502 
503   keys[0] = PythonString(key_0);
504   keys[1] = PythonString(key_1);
505   values[0] = PythonInteger(value_0);
506   values[1] = PythonString(value_1);
507 
508   PythonDictionary dict(PyInitialValue::Empty);
509   for (int i = 0; i < 2; ++i)
510     dict.SetItemForKey(keys[i], values[i]);
511 
512   EXPECT_EQ(dict_entries, dict.GetSize());
513   EXPECT_FALSE(dict.HasKey("not_in_dict"));
514   EXPECT_TRUE(dict.HasKey(key_0));
515   EXPECT_TRUE(dict.HasKey(key_1));
516 
517   // Verify that the keys and values match
518   PythonObject chk_value1 = dict.GetItemForKey(keys[0]);
519   PythonObject chk_value2 = dict.GetItemForKey(keys[1]);
520   EXPECT_TRUE(PythonInteger::Check(chk_value1.get()));
521   EXPECT_TRUE(PythonString::Check(chk_value2.get()));
522 
523   auto chkint = As<long long>(chk_value1);
524   PythonString chk_str(PyRefType::Borrowed, chk_value2.get());
525 
526   EXPECT_THAT_EXPECTED(chkint, llvm::HasValue(value_0));
527   EXPECT_EQ(value_1, chk_str.GetString());
528 }
529 
530 TEST_F(PythonDataObjectsTest, TestPythonDictionaryToStructuredDictionary) {
531   static const char *const string_key0 = "String Key 0";
532   static const char *const string_key1 = "String Key 1";
533 
534   static const char *const string_value0 = "String Value 0";
535   static const long int_value1 = 7;
536 
537   PythonDictionary dict(PyInitialValue::Empty);
538   dict.SetItemForKey(PythonString(string_key0), PythonString(string_value0));
539   dict.SetItemForKey(PythonString(string_key1), PythonInteger(int_value1));
540 
541   auto dict_sp = dict.CreateStructuredDictionary();
542   EXPECT_EQ(2U, dict_sp->GetSize());
543 
544   EXPECT_TRUE(dict_sp->HasKey(string_key0));
545   EXPECT_TRUE(dict_sp->HasKey(string_key1));
546 
547   auto string_sp = dict_sp->GetValueForKey(string_key0)->GetAsString();
548   auto int_sp = dict_sp->GetValueForKey(string_key1)->GetAsUnsignedInteger();
549 
550   EXPECT_EQ(string_value0, string_sp->GetValue());
551   EXPECT_EQ(int_value1, long(int_sp->GetValue()));
552 }
553 
554 TEST_F(PythonDataObjectsTest, TestPythonCallableCheck) {
555   PythonObject sys_exc_info = m_sys_module.ResolveName("exc_info");
556   PythonObject none(PyRefType::Borrowed, Py_None);
557 
558   EXPECT_TRUE(PythonCallable::Check(sys_exc_info.get()));
559   EXPECT_FALSE(PythonCallable::Check(none.get()));
560 }
561 
562 TEST_F(PythonDataObjectsTest, TestPythonCallableInvoke) {
563   auto list = m_builtins_module.ResolveName("list").AsType<PythonCallable>();
564   PythonInteger one(1);
565   PythonString two("two");
566   PythonTuple three = {one, two};
567 
568   PythonTuple tuple_to_convert = {one, two, three};
569   PythonObject result = list({tuple_to_convert});
570 
571   EXPECT_TRUE(PythonList::Check(result.get()));
572   auto list_result = result.AsType<PythonList>();
573   EXPECT_EQ(3U, list_result.GetSize());
574   EXPECT_EQ(one.get(), list_result.GetItemAtIndex(0).get());
575   EXPECT_EQ(two.get(), list_result.GetItemAtIndex(1).get());
576   EXPECT_EQ(three.get(), list_result.GetItemAtIndex(2).get());
577 }
578 
579 TEST_F(PythonDataObjectsTest, TestPythonFile) {
580   auto file = FileSystem::Instance().Open(FileSpec(FileSystem::DEV_NULL),
581                                           File::eOpenOptionReadOnly);
582   ASSERT_THAT_EXPECTED(file, llvm::Succeeded());
583   auto py_file = PythonFile::FromFile(*file.get(), "r");
584   ASSERT_THAT_EXPECTED(py_file, llvm::Succeeded());
585   EXPECT_TRUE(PythonFile::Check(py_file.get().get()));
586 }
587 
588 TEST_F(PythonDataObjectsTest, TestObjectAttributes) {
589   PythonInteger py_int(42);
590   EXPECT_TRUE(py_int.HasAttribute("numerator"));
591   EXPECT_FALSE(py_int.HasAttribute("this_should_not_exist"));
592 
593   auto numerator_attr = As<long long>(py_int.GetAttributeValue("numerator"));
594 
595   EXPECT_THAT_EXPECTED(numerator_attr, llvm::HasValue(42));
596 }
597 
598 TEST_F(PythonDataObjectsTest, TestExtractingUInt64ThroughStructuredData) {
599   // Make up a custom dictionary with "sys" pointing to the `sys` module.
600   const char *key_name = "addr";
601   const uint64_t value = 0xf000000000000000ull;
602   PythonDictionary python_dict(PyInitialValue::Empty);
603   PythonInteger python_ull_value(PyRefType::Owned,
604                                  PyLong_FromUnsignedLongLong(value));
605   python_dict.SetItemForKey(PythonString(key_name), python_ull_value);
606   StructuredData::ObjectSP structured_data_sp =
607       python_dict.CreateStructuredObject();
608   EXPECT_TRUE((bool)structured_data_sp);
609   if (structured_data_sp) {
610     StructuredData::Dictionary *structured_dict_ptr =
611         structured_data_sp->GetAsDictionary();
612     EXPECT_TRUE(structured_dict_ptr != nullptr);
613     if (structured_dict_ptr) {
614       StructuredData::ObjectSP structured_addr_value_sp =
615           structured_dict_ptr->GetValueForKey(key_name);
616       EXPECT_TRUE((bool)structured_addr_value_sp);
617       const uint64_t extracted_value =
618           structured_addr_value_sp->GetUnsignedIntegerValue(123);
619       EXPECT_TRUE(extracted_value == value);
620     }
621   }
622 }
623 
624 TEST_F(PythonDataObjectsTest, TestCallable) {
625 
626   PythonDictionary globals(PyInitialValue::Empty);
627   auto builtins = PythonModule::BuiltinsModule();
628   llvm::Error error = globals.SetItem("__builtins__", builtins);
629   ASSERT_FALSE(error);
630 
631   {
632     PyObject *o = PyRun_String("lambda x : x", Py_eval_input, globals.get(),
633                                globals.get());
634     ASSERT_FALSE(o == NULL);
635     auto lambda = Take<PythonCallable>(o);
636     auto arginfo = lambda.GetArgInfo();
637     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
638     EXPECT_EQ(arginfo.get().max_positional_args, 1u);
639   }
640 
641   {
642     PyObject *o = PyRun_String("lambda x,y=0: x", Py_eval_input, globals.get(),
643                                globals.get());
644     ASSERT_FALSE(o == NULL);
645     auto lambda = Take<PythonCallable>(o);
646     auto arginfo = lambda.GetArgInfo();
647     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
648     EXPECT_EQ(arginfo.get().max_positional_args, 2u);
649   }
650 
651   {
652     PyObject *o = PyRun_String("lambda x,y=0, **kw: x", Py_eval_input,
653                                globals.get(), globals.get());
654     ASSERT_FALSE(o == NULL);
655     auto lambda = Take<PythonCallable>(o);
656     auto arginfo = lambda.GetArgInfo();
657     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
658     EXPECT_EQ(arginfo.get().max_positional_args, 2u);
659   }
660 
661   {
662     PyObject *o = PyRun_String("lambda x,y,*a: x", Py_eval_input, globals.get(),
663                                globals.get());
664     ASSERT_FALSE(o == NULL);
665     auto lambda = Take<PythonCallable>(o);
666     auto arginfo = lambda.GetArgInfo();
667     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
668     EXPECT_EQ(arginfo.get().max_positional_args,
669               PythonCallable::ArgInfo::UNBOUNDED);
670   }
671 
672   {
673     PyObject *o = PyRun_String("lambda x,y,*a,**kw: x", Py_eval_input,
674                                globals.get(), globals.get());
675     ASSERT_FALSE(o == NULL);
676     auto lambda = Take<PythonCallable>(o);
677     auto arginfo = lambda.GetArgInfo();
678     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
679     EXPECT_EQ(arginfo.get().max_positional_args,
680               PythonCallable::ArgInfo::UNBOUNDED);
681   }
682 
683   {
684     const char *script = R"(
685 class Foo:
686   def bar(self, x):
687      return x
688   @classmethod
689   def classbar(cls, x):
690      return x
691   @staticmethod
692   def staticbar(x):
693      return x
694   def __call__(self, x):
695      return x
696 obj = Foo()
697 bar_bound   = Foo().bar
698 bar_class   = Foo().classbar
699 bar_static  = Foo().staticbar
700 bar_unbound = Foo.bar
701 
702 
703 class OldStyle:
704   def __init__(self, one, two, three):
705     pass
706 
707 class NewStyle(object):
708   def __init__(self, one, two, three):
709     pass
710 
711 )";
712     PyObject *o =
713         PyRun_String(script, Py_file_input, globals.get(), globals.get());
714     ASSERT_FALSE(o == NULL);
715     Take<PythonObject>(o);
716 
717     auto bar_bound = As<PythonCallable>(globals.GetItem("bar_bound"));
718     ASSERT_THAT_EXPECTED(bar_bound, llvm::Succeeded());
719     auto arginfo = bar_bound.get().GetArgInfo();
720     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
721     EXPECT_EQ(arginfo.get().max_positional_args, 1u);
722 
723     auto bar_unbound = As<PythonCallable>(globals.GetItem("bar_unbound"));
724     ASSERT_THAT_EXPECTED(bar_unbound, llvm::Succeeded());
725     arginfo = bar_unbound.get().GetArgInfo();
726     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
727     EXPECT_EQ(arginfo.get().max_positional_args, 2u);
728 
729     auto bar_class = As<PythonCallable>(globals.GetItem("bar_class"));
730     ASSERT_THAT_EXPECTED(bar_class, llvm::Succeeded());
731     arginfo = bar_class.get().GetArgInfo();
732     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
733     EXPECT_EQ(arginfo.get().max_positional_args, 1u);
734 
735     auto bar_static = As<PythonCallable>(globals.GetItem("bar_static"));
736     ASSERT_THAT_EXPECTED(bar_static, llvm::Succeeded());
737     arginfo = bar_static.get().GetArgInfo();
738     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
739     EXPECT_EQ(arginfo.get().max_positional_args, 1u);
740 
741     auto obj = As<PythonCallable>(globals.GetItem("obj"));
742     ASSERT_THAT_EXPECTED(obj, llvm::Succeeded());
743     arginfo = obj.get().GetArgInfo();
744     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
745     EXPECT_EQ(arginfo.get().max_positional_args, 1u);
746 
747     auto oldstyle = As<PythonCallable>(globals.GetItem("OldStyle"));
748     ASSERT_THAT_EXPECTED(oldstyle, llvm::Succeeded());
749     arginfo = oldstyle.get().GetArgInfo();
750     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
751     EXPECT_EQ(arginfo.get().max_positional_args, 3u);
752 
753     auto newstyle = As<PythonCallable>(globals.GetItem("NewStyle"));
754     ASSERT_THAT_EXPECTED(newstyle, llvm::Succeeded());
755     arginfo = newstyle.get().GetArgInfo();
756     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
757     EXPECT_EQ(arginfo.get().max_positional_args, 3u);
758   }
759 
760 #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
761 
762   // the old implementation of GetArgInfo just doesn't work on builtins.
763 
764   {
765     auto builtins = PythonModule::BuiltinsModule();
766     auto hex = As<PythonCallable>(builtins.GetAttribute("hex"));
767     ASSERT_THAT_EXPECTED(hex, llvm::Succeeded());
768     auto arginfo = hex.get().GetArgInfo();
769     ASSERT_THAT_EXPECTED(arginfo, llvm::Succeeded());
770     EXPECT_EQ(arginfo.get().max_positional_args, 1u);
771   }
772 
773 #endif
774 }
775 
776 TEST_F(PythonDataObjectsTest, TestScript) {
777 
778   static const char script[] = R"(
779 def factorial(n):
780   if n > 1:
781     return n * factorial(n-1)
782   else:
783     return 1;
784 main = factorial
785 )";
786 
787   PythonScript factorial(script);
788 
789   EXPECT_THAT_EXPECTED(As<long long>(factorial(5ll)), llvm::HasValue(120));
790 }
791 
792 TEST_F(PythonDataObjectsTest, TestExceptions) {
793 
794   static const char script[] = R"(
795 def foo():
796   return bar()
797 def bar():
798   return baz()
799 def baz():
800   return 1 / 0
801 main = foo
802 )";
803 
804   PythonScript foo(script);
805 
806   EXPECT_THAT_EXPECTED(
807       foo(), llvm::Failed<PythonException>(testing::Property(
808                  &PythonException::ReadBacktrace,
809                  testing::AllOf(testing::ContainsRegex("line 3, in foo"),
810                                 testing::ContainsRegex("line 5, in bar"),
811                                 testing::ContainsRegex("line 7, in baz"),
812                                 testing::ContainsRegex("ZeroDivisionError")))));
813 
814 #if !((defined(_WIN32) || defined(_WIN64)) && (defined(__aarch64__) || defined(_M_ARM64)))
815 
816   static const char script2[] = R"(
817 class MyError(Exception):
818   def __str__(self):
819     return self.my_message
820 
821 def main():
822   raise MyError("lol")
823 
824 )";
825 
826   PythonScript lol(script2);
827 
828   EXPECT_THAT_EXPECTED(
829       lol(),
830       llvm::Failed<PythonException>(testing::Property(
831           &PythonException::ReadBacktrace,
832           testing::AnyOf(
833               testing::ContainsRegex("MyError: <exception str\\(\\) failed>"),
834               testing::ContainsRegex("unprintable MyError")))));
835 
836 #endif
837 }
838 
839 TEST_F(PythonDataObjectsTest, TestRun) {
840 
841   PythonDictionary globals(PyInitialValue::Empty);
842 
843   auto x = As<long long>(runStringOneLine("40 + 2", globals, globals));
844   ASSERT_THAT_EXPECTED(x, llvm::Succeeded());
845   EXPECT_EQ(x.get(), 42l);
846 
847   Expected<PythonObject> r = runStringOneLine("n = 42", globals, globals);
848   ASSERT_THAT_EXPECTED(r, llvm::Succeeded());
849   auto y = As<long long>(globals.GetItem("n"));
850   ASSERT_THAT_EXPECTED(y, llvm::Succeeded());
851   EXPECT_EQ(y.get(), 42l);
852 
853   const char script[] = R"(
854 def foobar():
855   return "foo" + "bar" + "baz"
856 g = foobar()
857 )";
858 
859   r = runStringMultiLine(script, globals, globals);
860   ASSERT_THAT_EXPECTED(r, llvm::Succeeded());
861   auto g = As<std::string>(globals.GetItem("g"));
862   ASSERT_THAT_EXPECTED(g, llvm::HasValue("foobarbaz"));
863 }
864