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