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