|
1 | 1 | #!/usr/bin/env python3
|
2 | 2 | # -*- coding: UTF-8 -*-
|
3 | 3 |
|
| 4 | +import pickle |
| 5 | + |
4 | 6 | import pytest
|
5 | 7 |
|
6 | 8 | import sentinel
|
7 | 9 |
|
| 10 | +# Must be defined at module-level due to limitations in how the pickle module works :/ |
| 11 | +Pickleable = sentinel.create("Pickleable") |
| 12 | + |
8 | 13 |
|
9 | 14 | def test_basic_usage():
|
10 | 15 | """
|
@@ -88,5 +93,34 @@ def test_always_greater():
|
88 | 93 | assert (AlwaysGreater < (1, ..., ...)) == False
|
89 | 94 |
|
90 | 95 |
|
91 |
| -# TODO: test pickling |
| 96 | +def test_new_returns_singleton(): |
| 97 | + """ |
| 98 | + Tests that getting the class and calling it returns the same singleton instance. |
| 99 | + """ |
| 100 | + ExistingSentinel = sentinel.create("ExistingSentinel") |
| 101 | + Constructor = type(ExistingSentinel) |
| 102 | + assert Constructor() is ExistingSentinel |
| 103 | + |
| 104 | + |
| 105 | +def test_pickle(tmp_path): |
| 106 | + """ |
| 107 | + Save a singleton to a pickle and get it back out. |
| 108 | + """ |
| 109 | + |
| 110 | + # Just put it everywhere: |
| 111 | + arbitrary_data_structure = {Pickleable: (Pickleable, [Pickleable])} |
| 112 | + |
| 113 | + pickle_path = tmp_path / "data.pickle" |
| 114 | + with pickle_path.open(mode="wb") as fp: |
| 115 | + pickle.dump(arbitrary_data_structure, fp) |
| 116 | + |
| 117 | + with pickle_path.open(mode="rb") as fp: |
| 118 | + unpickled = pickle.load(fp) |
| 119 | + |
| 120 | + # Open up the data structure |
| 121 | + assert Pickleable in unpickled |
| 122 | + assert unpickled[Pickleable][0] is Pickleable |
| 123 | + assert unpickled[Pickleable][1][0] is Pickleable |
| 124 | + |
| 125 | + |
92 | 126 | # TODO: test copy() and deepcopy()
|
0 commit comments