| 2390 | ] |
| 2391 | ) |
| 2392 | def test_table_from_pydict(cls): |
| 2393 | table = cls.from_pydict({}) |
| 2394 | assert table.num_columns == 0 |
| 2395 | assert table.num_rows == 0 |
| 2396 | assert table.schema == pa.schema([]) |
| 2397 | assert table.to_pydict() == {} |
| 2398 | |
| 2399 | schema = pa.schema([('strs', pa.utf8()), ('floats', pa.float64())]) |
| 2400 | |
| 2401 | # With lists as values |
| 2402 | data = OrderedDict([('strs', ['', 'foo', 'bar']), |
| 2403 | ('floats', [4.5, 5, None])]) |
| 2404 | table = cls.from_pydict(data) |
| 2405 | assert table.num_columns == 2 |
| 2406 | assert table.num_rows == 3 |
| 2407 | assert table.schema == schema |
| 2408 | assert table.to_pydict() == data |
| 2409 | |
| 2410 | # With metadata and inferred schema |
| 2411 | metadata = {b'foo': b'bar'} |
| 2412 | schema = schema.with_metadata(metadata) |
| 2413 | table = cls.from_pydict(data, metadata=metadata) |
| 2414 | assert table.schema == schema |
| 2415 | assert table.schema.metadata == metadata |
| 2416 | assert table.to_pydict() == data |
| 2417 | |
| 2418 | # With explicit schema |
| 2419 | table = cls.from_pydict(data, schema=schema) |
| 2420 | assert table.schema == schema |
| 2421 | assert table.schema.metadata == metadata |
| 2422 | assert table.to_pydict() == data |
| 2423 | |
| 2424 | # Cannot pass both schema and metadata |
| 2425 | with pytest.raises(ValueError): |
| 2426 | cls.from_pydict(data, schema=schema, metadata=metadata) |
| 2427 | |
| 2428 | # Non-convertible values given schema |
| 2429 | with pytest.raises(TypeError): |
| 2430 | cls.from_pydict({'c0': [0, 1, 2]}, |
| 2431 | schema=pa.schema([("c0", pa.string())])) |
| 2432 | |
| 2433 | # Missing schema fields from the passed mapping |
| 2434 | with pytest.raises(KeyError, match="doesn\'t contain.* c, d"): |
| 2435 | cls.from_pydict( |
| 2436 | {'a': [1, 2, 3], 'b': [3, 4, 5]}, |
| 2437 | schema=pa.schema([ |
| 2438 | ('a', pa.int64()), |
| 2439 | ('c', pa.int32()), |
| 2440 | ('d', pa.int16()) |
| 2441 | ]) |
| 2442 | ) |
| 2443 | |
| 2444 | # Passed wrong schema type |
| 2445 | with pytest.raises(TypeError): |
| 2446 | cls.from_pydict({'a': [1, 2, 3]}, schema={}) |
| 2447 | |
| 2448 | |
| 2449 | @pytest.mark.parametrize('data, klass', [ |