tkintertester 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,121 @@
1
+ Creative Commons Legal Code
2
+
3
+ CC0 1.0 Universal
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
@@ -0,0 +1,323 @@
1
+ Metadata-Version: 2.4
2
+ Name: tkintertester
3
+ Version: 0.1.0
4
+ Summary: A minimal, event-loop-native test harness for Tkinter GUI applications
5
+ Author: Lion Kimbro
6
+ License-Expression: CC0-1.0
7
+ Project-URL: Repository, https://github.com/LionKimbro/tkintertester
8
+ Keywords: tkinter,testing,gui,test-harness
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.8
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Testing
20
+ Classifier: Topic :: Software Development :: User Interfaces
21
+ Requires-Python: >=3.8
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Dynamic: license-file
25
+
26
+ # tkintertester
27
+
28
+ A minimal, event-loop-native test harness for Tkinter GUI applications.
29
+
30
+ ## The Problem
31
+
32
+ Tkinter doesn't play well with traditional testing approaches:
33
+
34
+ 1. **Tk can't restart cleanly.** Once you destroy a Tk root and try to create another in the same process, things break. This makes pytest/unittest fixtures that create and tear down Tk windows unreliable or impossible.
35
+
36
+ 2. **Tk runs a blocking event loop.** You can't just "call" your GUI from test code and inspect it—that blocks the mainloop or requires threading/async complexity.
37
+
38
+ 3. **Tk silently swallows exceptions.** Exceptions in callbacks get printed to stderr but don't propagate—your test keeps running even though something failed.
39
+
40
+ ## The Solution
41
+
42
+ Run tests *inside* the Tk event loop itself.
43
+
44
+ - One process, one thread, one `mainloop()`
45
+ - Tests execute as sequences of **step functions** scheduled via `root.after()`
46
+ - Step functions return control immediately—they never block
47
+ - The harness manages test progression, timeouts, and results
48
+ - Exceptions in callbacks are caught and fail the current test
49
+
50
+ ## Design Principles
51
+
52
+ - **No async/await** — step-based execution driven by return values
53
+ - **No classes** — global functions and dictionaries
54
+ - **No simulation** — tests run in the real Tk event loop
55
+ - **Lightweight harness** — doesn't own or track your widgets
56
+
57
+ ## Installation
58
+
59
+ ```bash
60
+ pip install -e .
61
+ ```
62
+
63
+ ## Quick Example
64
+
65
+ ```python
66
+ import tkinter
67
+ from tkinter import ttk
68
+ from tkintertester import harness
69
+
70
+ # Application state
71
+ app = {"count": 0, "toplevel": None}
72
+ widgets = {}
73
+
74
+ def entry():
75
+ """Set up the app."""
76
+ app["count"] = 0
77
+ app["toplevel"] = tkinter.Toplevel(harness.g["root"])
78
+ widgets["label"] = ttk.Label(app["toplevel"], text="0")
79
+ widgets["label"].grid(row=0, column=0)
80
+ widgets["button"] = ttk.Button(
81
+ app["toplevel"], text="+1",
82
+ command=lambda: increment()
83
+ )
84
+ widgets["button"].grid(row=1, column=0)
85
+
86
+ def reset():
87
+ """Reset between tests."""
88
+ app["toplevel"].destroy()
89
+ widgets.clear()
90
+
91
+ def increment():
92
+ app["count"] += 1
93
+ widgets["label"].config(text=str(app["count"]))
94
+
95
+ # Define a test
96
+ def test_increment():
97
+ def step_click():
98
+ widgets["button"].invoke()
99
+ return ("next", None)
100
+
101
+ def step_verify():
102
+ if widgets["label"].cget("text") == "1":
103
+ return ("success", None)
104
+ return ("fail", "Counter should be 1")
105
+
106
+ return [step_click, step_verify]
107
+
108
+ # Run
109
+ harness.add_test("Increment counter", test_increment())
110
+ harness.set_resetfn(reset)
111
+ harness.set_timeout(5000)
112
+ harness.run_host(entry, flags="x")
113
+ harness.print_results()
114
+ ```
115
+
116
+ ## API Reference
117
+
118
+ ### Test Registration
119
+
120
+ ```python
121
+ harness.add_test(title, steps)
122
+ ```
123
+ Register a test. `steps` is a list of nullary step functions.
124
+
125
+ ### Configuration
126
+
127
+ ```python
128
+ harness.set_timeout(timeout_ms)
129
+ ```
130
+ Set the timeout for each test (default: 5000ms).
131
+
132
+ ```python
133
+ harness.set_resetfn(app_reset)
134
+ ```
135
+ Set a function to call between tests (to reset/clean up UI state).
136
+
137
+ ### Running Tests
138
+
139
+ ```python
140
+ harness.run_host(app_entry, flags="")
141
+ ```
142
+ Harness creates a hidden Tk root and owns the lifecycle. Runs all registered tests, calling `app_entry()` before each test and `app_reset()` (if set) after each test. After all tests complete:
143
+ - If `"x"` in flags: exit mainloop
144
+ - Otherwise: call `app_entry()` one more time to transition into normal runtime
145
+
146
+ Flags:
147
+ - `"x"` — exit after tests complete
148
+ - `"s"` — show results in a Tk window after tests complete
149
+
150
+ ```python
151
+ harness.attach_harness(root, flags="")
152
+ ```
153
+ Attach the harness to an already-running application's root window. Tests run immediately. The `"x"` flag is not allowed (you can't exit an app you don't own).
154
+
155
+ ### Results
156
+
157
+ ```python
158
+ harness.get_results() # Returns formatted string
159
+ harness.print_results() # Prints to stdout
160
+ harness.write_results(filepath) # Writes to file
161
+ harness.show_results() # Displays in a Tk window
162
+ ```
163
+
164
+ ### Accessing State
165
+
166
+ ```python
167
+ harness.tests # List of test dictionaries (with results after execution)
168
+ harness.g # Harness state dictionary (includes g["root"])
169
+ ```
170
+
171
+ ## Step Function Contract
172
+
173
+ Each step is a nullary function that returns `(action, value)`:
174
+
175
+ | Action | Value | Meaning |
176
+ |--------|-------|---------|
177
+ | `"next"` | `None` | Advance to next step immediately |
178
+ | `"next"` | `int` | Advance after N milliseconds |
179
+ | `"wait"` | `int` | Retry this step after N milliseconds |
180
+ | `"goto"` | `int` | Jump to step at index N |
181
+ | `"success"` | `None` | Test passed |
182
+ | `"success"` | `int` | Test passed, finalize after N ms |
183
+ | `"fail"` | `str` | Test failed with message |
184
+
185
+ If all steps complete without explicit `"success"` or `"fail"`, the test is considered successful.
186
+
187
+ ## Exception Handling
188
+
189
+ The harness overrides `root.report_callback_exception` to catch exceptions in Tk callbacks. If an exception occurs during a test (in a button handler, `after()` callback, event binding, etc.), the test is immediately marked as failed with the exception traceback captured.
190
+
191
+ ## Test Lifecycle
192
+
193
+ **With `run_host()`:**
194
+
195
+ 1. Harness creates a hidden Tk root and enters `mainloop()`
196
+ 2. For each test:
197
+ - Call `app_entry()` (create windows, widgets)
198
+ - Execute steps until success, failure, or timeout
199
+ - Record result in the test object
200
+ - Call `app_reset()` if set (clean up for next test)
201
+ 3. After all tests:
202
+ - If `"s"` flag: show results window
203
+ - If `"x"` flag: exit mainloop
204
+ - Otherwise: call `app_entry()` to transition into normal app runtime
205
+
206
+ **With `attach_harness()`:**
207
+
208
+ 1. Attach to existing root window
209
+ 2. Run tests immediately
210
+ 3. After all tests: app continues running (no exit)
211
+
212
+ ## Two-Track Testing Strategy
213
+
214
+ For larger applications (20+ files), split tests into two tracks:
215
+
216
+ - **Track 1: Logic tests** — Pure functions, data processing, validation. Use pytest normally; no Tk needed.
217
+ - **Track 2: GUI tests** — Widget behavior, user interactions. Use tkintertester.
218
+
219
+ This separation encourages keeping business logic out of GUI code.
220
+
221
+ ## Structuring Your App for Testing
222
+
223
+ Design your app with `entry()` and `reset()` functions. The CLI or main script sets up the root and calls entry. Tests use the harness.
224
+
225
+ ```python
226
+ # myapp/main.py
227
+ import tkinter as tk
228
+
229
+ g = {"count": 0}
230
+ widgets = {}
231
+ app = {"root": None, "toplevel": None}
232
+
233
+ def entry():
234
+ """Create the UI. app['root'] must be set before calling."""
235
+ g["count"] = 0
236
+ app["toplevel"] = tk.Toplevel(app["root"])
237
+ widgets["label"] = tk.Label(app["toplevel"], text="0")
238
+ widgets["label"].grid(row=0, column=0)
239
+ widgets["button"] = tk.Button(
240
+ app["toplevel"], text="+1",
241
+ command=handle_when_user_clicks_increment
242
+ )
243
+ widgets["button"].grid(row=1, column=0)
244
+
245
+ def reset():
246
+ """Tear down the UI between tests."""
247
+ app["toplevel"].destroy()
248
+ widgets.clear()
249
+
250
+ def handle_when_user_clicks_increment():
251
+ g["count"] += 1
252
+ widgets["label"].config(text=str(g["count"]))
253
+ ```
254
+
255
+ ## Recommended Project Layout
256
+
257
+ Keep pytest tests and GUI tests in separate directories:
258
+
259
+ ```
260
+ myproject/
261
+ src/
262
+ myapp/
263
+ __init__.py
264
+ main.py # has entry(), reset()
265
+ logic.py # pure functions, no Tk dependency
266
+ tests/ # pytest: logic tests (Track 1)
267
+ test_logic.py
268
+ guitests/ # tkintertester: GUI tests (Track 2)
269
+ test_main_window.py
270
+ pyproject.toml
271
+ ```
272
+
273
+ Configure pytest to only discover tests in `tests/`:
274
+
275
+ ```toml
276
+ # pyproject.toml
277
+ [tool.pytest.ini_options]
278
+ testpaths = ["tests"]
279
+ ```
280
+
281
+ A GUI test file imports the app and uses the harness:
282
+
283
+ ```python
284
+ # guitests/test_main_window.py
285
+ from tkintertester import harness
286
+ from myapp import main as app
287
+
288
+ def test_increment():
289
+ def step_click():
290
+ app.widgets["button"].invoke()
291
+ return ("next", None)
292
+
293
+ def step_verify():
294
+ if app.widgets["label"].cget("text") == "1":
295
+ return ("success", None)
296
+ return ("fail", "Counter should be 1")
297
+
298
+ return [step_click, step_verify]
299
+
300
+ def app_entry():
301
+ app.app["root"] = harness.g["root"]
302
+ app.entry()
303
+
304
+ harness.add_test("Increment counter", test_increment())
305
+ harness.set_resetfn(app.reset)
306
+ harness.run_host(app_entry, flags="x")
307
+ harness.print_results()
308
+ ```
309
+
310
+ Running tests:
311
+
312
+ ```bash
313
+ python -m pytest # runs logic tests (Track 1)
314
+ python guitests/test_main_window.py # runs GUI tests (Track 2)
315
+ ```
316
+
317
+ ## Full Documentation
318
+
319
+ [docs/reference.md](docs/reference.md)
320
+
321
+ ## License
322
+
323
+ CC0 1.0 Universal — Public Domain