zizek 0.1.0

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.
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,201 @@
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/zizek-rb-logo-dark.svg">
4
+ <img src="docs/assets/zizek-rb-logo.svg" alt="Zizek.rb" width="320">
5
+ </picture>
6
+ </p>
7
+
8
+ # Zizek for Ruby
9
+
10
+ This gem is the native Ruby runtime for Zizek property testing, based on
11
+ [Hegel](https://hegel.dev) and
12
+ [Hypothesis](https://hypothesis.readthedocs.io/en/latest/) and keeping them
13
+ as oracle implementations. It explores generated examples, records every
14
+ choice, shrinks the first failure, and raises a failure containing a portable
15
+ reproduce blob.
16
+
17
+ Roughly two thirds of the core behavior is compiled from the Hegel engine into
18
+ `lib/zizek/gen.rb`; the rest is a curated shell that aims to be idiomatic Ruby.
19
+ [dev.md](dev.md) describes the split.
20
+
21
+ > ⚠️ **Status: experimental.** Behavior and the public API can still change and
22
+ > be tweaked between releases.
23
+
24
+ ## Install
25
+
26
+ ```bash
27
+ gem install zizek
28
+ ```
29
+
30
+ Or, in a `Gemfile`:
31
+
32
+ ```ruby
33
+ gem "zizek", "~> 0.1"
34
+ ```
35
+
36
+ ## Quick start
37
+
38
+ ```ruby
39
+ require "zizek"
40
+
41
+ property = lambda do |test_case|
42
+ value = test_case.draw(Zizek::Generators.integers(-100..100), name: :value)
43
+ raise "too large" unless value < 5
44
+ end
45
+
46
+ begin
47
+ Zizek.check(property, examples: 200, seed: 1)
48
+ rescue Zizek::Failure => failure
49
+ puts failure.message
50
+
51
+ # Runs exactly the recorded, shrunk example and raises Failure again.
52
+ begin
53
+ Zizek.check(property, reproduce: failure.blob)
54
+ rescue Zizek::Failure
55
+ end
56
+ end
57
+ ```
58
+
59
+ The failure says which values failed, not just that something did:
60
+
61
+ ```
62
+ Falsifying example: (value=5)
63
+ RuntimeError: too large
64
+ reproduce with: Zizek.check(property, reproduce: "AAEAAAAACgEAAAAF")
65
+ seed: 1
66
+ ```
67
+
68
+ `Zizek.check` also accepts a block, and `Zizek.run` returns the verdict as a
69
+ value instead of raising:
70
+
71
+ ```ruby
72
+ Zizek.check(examples: 200) do |test_case|
73
+ raise "too large" unless test_case.draw(Zizek::Generators.integers(-100..100)) < 5
74
+ end
75
+
76
+ Zizek.run(property, examples: 200, seed: 1).blob # => "AAEAAAAACgEAAAAF"
77
+ ```
78
+
79
+ ## Generators
80
+
81
+ Generators compose with `map`, `filter`, `|`, and `tuples`, and add no hidden
82
+ choices, so a composed value shrinks and replays like a plain one:
83
+
84
+ ```ruby
85
+ g = Zizek::Generators
86
+
87
+ request = g.tuples(
88
+ g.sampled_from(%i[get post delete]),
89
+ g.none | g.text(min: 1, max: 8),
90
+ g.integers(0..10).filter(&:even?)
91
+ )
92
+
93
+ Zizek.check(examples: 200, seed: 7) do |test_case|
94
+ method, resource, _retries = test_case.draw(request)
95
+ raise "DELETE must name a resource" if method == :delete && resource.nil?
96
+ end
97
+ ```
98
+
99
+ ## Test frameworks
100
+
101
+ With Minitest, `property` defines a real test method:
102
+
103
+ ```ruby
104
+ require "zizek/minitest"
105
+
106
+ class SplitBillTest < Minitest::Test
107
+ include Zizek::Minitest
108
+
109
+ property "the split is exact",
110
+ total: Zizek::Generators.integers(0..10_000),
111
+ people: Zizek::Generators.integers(1..50) do |total, people|
112
+ assert_equal total, Bill.split(total, people).sum
113
+ end
114
+ end
115
+ ```
116
+
117
+ With RSpec, it defines a real example:
118
+
119
+ ```ruby
120
+ require "zizek/rspec"
121
+
122
+ RSpec.describe Bill do
123
+ property "the split is exact",
124
+ total: Zizek::Generators.integers(0..10_000),
125
+ people: Zizek::Generators.integers(1..50) do |total, people|
126
+ expect(described_class.split(total, people).sum).to eq(total)
127
+ end
128
+ end
129
+ ```
130
+
131
+ ## Stateful testing
132
+
133
+ Subclass `Zizek::Stateful::Machine` and declare rules and invariants; a
134
+ failure shrinks to the shortest sequence of steps that still fails:
135
+
136
+ ```ruby
137
+ class Counter < Zizek::Stateful::Machine
138
+ def initialize
139
+ @value = 0
140
+ end
141
+
142
+ rule(:increment) do |test_case|
143
+ @value += test_case.draw(Zizek::Generators.integers(0..10), name: :amount)
144
+ end
145
+
146
+ rule(:decrement) do |test_case|
147
+ test_case.assume(@value.positive?)
148
+ @value -= 1
149
+ end
150
+
151
+ invariant(:nonnegative) do
152
+ raise "negative" if @value.negative?
153
+ end
154
+ end
155
+
156
+ Zizek.check(Counter.property, examples: 500)
157
+ ```
158
+
159
+ ## Learn more
160
+
161
+ - [GUIDE.md](GUIDE.md) walks through every feature with runnable examples:
162
+ settings and profiles, the example database, keyed draws, coverage
163
+ assertions, pools, and more.
164
+ - [`examples/`](examples) holds runnable examples; each is listed in the
165
+ guide.
166
+ - [dev.md](dev.md) covers the package layout, verification, and the upstream
167
+ example ports.
168
+ - [CHANGELOG.md](CHANGELOG.md) records each release.
169
+
170
+ ## Functionality available now
171
+
172
+ - Sequential property exploration with deterministic seeds.
173
+ - Generation-phase mutation that duplicates same-label spans to discover
174
+ repeated values and repeated state-machine operations.
175
+ - Recorded integer, boolean, byte-string, IEEE-754 float, and Unicode text choices.
176
+ - Uniform narrow integer draws and swarm-biased wide ones.
177
+ - Composable generators accepted by `test_case.draw`.
178
+ - Assumption-based rejection with configurable limits.
179
+ - Exception and returned-`false` failure capture.
180
+ - Variable-length `Generators.lists` whose elements shrink by deletion, plus
181
+ `Generators.sets`, `Generators.hashes`, and `lists(unique_by:)` for distinct
182
+ elements.
183
+ - Per-choice shrinking plus element-span and rule-span deletion.
184
+ - Cloned streams: `test_case.clone_stream` returns a child test case drawing from
185
+ a stream of its own, framed in the parent's blob and shrunk by the same
186
+ schedule.
187
+ - Portable replay with choice punning and overrun detection, with punned
188
+ draws counted and reported on the failure.
189
+ - An example database that stores counterexamples between runs and replays them
190
+ before generating — in a layout the Python and Go packages share.
191
+ - State machines as classes (`Zizek::Stateful::Machine` with `rule` and
192
+ `invariant`) or as hand-built rule arrays, with a default budget of 50
193
+ successful steps (rejected rules spend an attempt, not a step).
194
+ - Reusable and consumed arbitrary Ruby-object pools.
195
+ - Named draws, reported as a falsifying example on the failure.
196
+ - Frozen `Settings` objects and named profiles, so a suite configures itself
197
+ once instead of at every call site.
198
+ - `Zizek.run` for the verdict as a value, alongside `Zizek.check`.
199
+ - Minitest and RSpec integrations that define real tests in each framework.
200
+ - Runnable ports of Hypothesis's introductory example and all five top-level
201
+ Hegel examples, including the ledger acceptance case.
@@ -0,0 +1,16 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="-70 -20 1040 970" width="1040" height="970" role="img" aria-label="Zizek.rb">
2
+ <title>Zizek.rb</title>
3
+ <!-- shrinking counterexample: each pass narrows the failing input until only
4
+ the minimal reproducer (the accent square) is left -->
5
+ <g>
6
+ <rect x="125" y="40" width="475" height="110" fill="#eef1fa"/>
7
+ <rect x="243" y="160" width="357" height="105" fill="#a9c4f7"/>
8
+ <rect x="363" y="273" width="230" height="94" fill="#5b9cf0"/>
9
+ <rect x="460" y="375" width="173" height="73" fill="#2f7ce6"/>
10
+ <rect x="545" y="455" width="130" height="65" fill="#1a5fd0"/>
11
+ <rect x="670" y="525" width="45" height="43" fill="#ff5f70"/>
12
+ </g>
13
+ <text x="450" y="880" fill="#eef1fa" text-anchor="middle"
14
+ font-family="'Helvetica Neue', Helvetica, Arial, 'Liberation Sans', sans-serif"
15
+ font-size="265" font-weight="600" letter-spacing="-5">&#381;i&#382;ek<tspan fill="#ff5f70">.rb</tspan></text>
16
+ </svg>
@@ -0,0 +1,16 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="-70 -20 1040 970" width="1040" height="970" role="img" aria-label="Zizek.rb">
2
+ <title>Zizek.rb</title>
3
+ <!-- shrinking counterexample: each pass narrows the failing input until only
4
+ the minimal reproducer (the accent square) is left -->
5
+ <g>
6
+ <rect x="125" y="40" width="475" height="110" fill="#17224e"/>
7
+ <rect x="243" y="160" width="357" height="105" fill="#0f47b4"/>
8
+ <rect x="363" y="273" width="230" height="94" fill="#2277e0"/>
9
+ <rect x="460" y="375" width="173" height="73" fill="#5b9cf0"/>
10
+ <rect x="545" y="455" width="130" height="65" fill="#7fb2f5"/>
11
+ <rect x="670" y="525" width="45" height="43" fill="#cc0f2b"/>
12
+ </g>
13
+ <text x="450" y="880" fill="#17224e" text-anchor="middle"
14
+ font-family="'Helvetica Neue', Helvetica, Arial, 'Liberation Sans', sans-serif"
15
+ font-size="265" font-weight="600" letter-spacing="-5">&#381;i&#382;ek<tspan fill="#cc0f2b">.rb</tspan></text>
16
+ </svg>
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Composing generators: the blob stays portable, the shrinker stays sharp.
4
+ #
5
+ # Demonstrates:
6
+ # - `builds` assembling a struct from drawn parts;
7
+ # - `sampled_from`, `map`, `filter`, and `|` (one_of) layered on top;
8
+ # - `composite` for a draw that depends on an earlier draw; and
9
+ # - shrinking straight through the composition: combinators add no hidden
10
+ # choices, so the minimal counterexample is minimal in every field at
11
+ # once.
12
+ #
13
+ # Both scenarios are deterministic: fixed seeds, printed shrunk failures.
14
+
15
+ require "zizek"
16
+
17
+ module CombinatorsExample
18
+ G = Zizek::Generators
19
+
20
+ Request = Struct.new(:verb, :path, :body, :retries)
21
+
22
+ module_function
23
+
24
+ # A generator per field, assembled with `builds`:
25
+ # - `sampled_from` picks a verb, shrinking towards the first;
26
+ # - `map` turns drawn text into a path without recording extra choices;
27
+ # - `|` makes the body optional, shrinking towards the left (nil) side;
28
+ # - `filter` keeps only even retry counts, rejecting rather than failing.
29
+ def requests
30
+ G.builds(
31
+ Request,
32
+ verb: G.sampled_from(%i[get put delete]),
33
+ path: G.text(min: 1, max: 8, alphabet: "abc").map { |name| "/#{name}" },
34
+ body: G.none | G.text(min: 1, max: 6, alphabet: "xyz"),
35
+ retries: G.integers(0..9).filter(&:even?)
36
+ )
37
+ end
38
+
39
+ # The bug: the router forwards a DELETE body instead of rejecting it. The
40
+ # shrunk request is minimal in every field the failure does not need —
41
+ # shortest path, smallest retries — while `verb` stays `:delete` and `body`
42
+ # stays present, because the failure needs them.
43
+ def delete_with_a_body
44
+ property = lambda do |test_case|
45
+ request = test_case.draw(requests, name: :request)
46
+ raise "refusing to forward a DELETE with a body" if
47
+ request.verb == :delete && !request.body.nil?
48
+ end
49
+
50
+ begin
51
+ Zizek.check(property, examples: 500, seed: 2)
52
+ raise "the DELETE-with-body bug should be discovered"
53
+ rescue Zizek::Failure => failure
54
+ failure
55
+ end
56
+ end
57
+
58
+ # `composite` is for a generator whose later draws depend on earlier ones:
59
+ # here a meeting that must end no earlier than it starts. The block gets
60
+ # the test case itself, so it can draw, assume, and note like a property.
61
+ def meetings
62
+ G.composite do |t|
63
+ starts = t.draw(G.integers(0..23))
64
+ ends = t.draw(G.integers(starts..23))
65
+ [starts, ends]
66
+ end
67
+ end
68
+
69
+ # The bug: the scheduler double-books the noon slot. The failure needs a
70
+ # meeting spanning hour 12, so the shrunk example is the earliest start
71
+ # with the earliest end that still covers it.
72
+ def meeting_across_noon
73
+ property = lambda do |test_case|
74
+ starts, ends = test_case.draw(meetings, name: :meeting)
75
+ test_case.note("meeting #{starts}:00-#{ends}:59")
76
+ raise "the noon slot was double-booked" if starts <= 12 && ends >= 12
77
+ end
78
+
79
+ begin
80
+ Zizek.check(property, examples: 300, seed: 1)
81
+ raise "the noon double-booking should be discovered"
82
+ rescue Zizek::Failure => failure
83
+ failure
84
+ end
85
+ end
86
+ end
87
+
88
+ if $PROGRAM_NAME == __FILE__
89
+ puts "== 1. builds + sampled_from + map + filter + | =="
90
+ puts CombinatorsExample.delete_with_a_body.message
91
+ puts "\n== 2. composite: dependent draws =="
92
+ puts CombinatorsExample.meeting_across_noon.message
93
+ end
@@ -0,0 +1,138 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Coverage assertions: catching the test that passes for the wrong reason.
4
+ #
5
+ # Demonstrates:
6
+ # - `always`, an ordinary failure that shrinks to the boundary it crossed;
7
+ # - `unreachable`, shrinking to the simplest input reaching a branch;
8
+ # - `sometimes`, failing a run whose interesting branch never executed;
9
+ # - `cover(percent:)`, requiring a rate rather than a single sighting; and
10
+ # - `must_cover:`, declaring a label whose call site itself may never run.
11
+ #
12
+ # The code under test is a clamp that forgot its ceiling. Every scenario is
13
+ # deterministic: it uses a fixed seed and prints the verdict it expects.
14
+
15
+ require "zizek"
16
+
17
+ module CoverageAssertionsExample
18
+ module_function
19
+
20
+ # Clamp `value` into [floor, ceiling]. Deliberate bug: the ceiling check
21
+ # compares against the floor, so values above the ceiling pass through.
22
+ def clamp(value, floor, ceiling)
23
+ return floor if value < floor
24
+ return ceiling if value < floor # BUG: should be `if value > ceiling`
25
+
26
+ value
27
+ end
28
+
29
+ # `always` is a per-example assertion. It fails like any other failure, so
30
+ # it shrinks: the reported example is the *smallest* value that escapes the
31
+ # ceiling, 101, not whatever large value was found first.
32
+ def always_shrinks_to_the_boundary
33
+ property = lambda do |test_case|
34
+ value = test_case.integer(0, 1000)
35
+ clamped = clamp(value, 0, 100)
36
+ test_case.always("clamped into range", clamped.between?(0, 100))
37
+ end
38
+
39
+ begin
40
+ Zizek.check(property, examples: 300, seed: 1)
41
+ raise "the broken ceiling should be discovered"
42
+ rescue Zizek::Failure => failure
43
+ failure
44
+ end
45
+ end
46
+
47
+ # `unreachable` asserts a branch is dead. When it is not, the failure
48
+ # shrinks to the simplest input that reaches it.
49
+ def unreachable_finds_the_simplest_path
50
+ property = lambda do |test_case|
51
+ value = test_case.integer(0, 1000)
52
+ test_case.unreachable("value escaped the clamp") if clamp(value, 0, 100) > 100
53
+ end
54
+
55
+ begin
56
+ Zizek.check(property, examples: 300, seed: 1)
57
+ raise "the escape branch should be reached"
58
+ rescue Zizek::Failure => failure
59
+ failure
60
+ end
61
+ end
62
+
63
+ # `sometimes` judges the completed run, not the current example. Here the
64
+ # property itself holds on every draw — the generator never exceeds the
65
+ # ceiling, so the clamp is never exercised where it is broken. Without the
66
+ # coverage assertion this run would go green and prove nothing.
67
+ def sometimes_fails_the_vacuous_pass
68
+ property = lambda do |test_case|
69
+ value = test_case.integer(0, 100) # never above the ceiling: too narrow
70
+ clamped = clamp(value, 0, 100)
71
+ test_case.sometimes("saturated at the ceiling", clamped == 100 && value > 100)
72
+ raise "clamp raised the value" if clamped > value
73
+ end
74
+
75
+ begin
76
+ Zizek.check(property, examples: 200, seed: 1)
77
+ raise "the run should fail its coverage requirement"
78
+ rescue Zizek::FailedCoverage => missed
79
+ missed
80
+ end
81
+ end
82
+
83
+ # `cover` is `sometimes` with a required rate over the run's valid examples.
84
+ # Values 0..1000 clamped into [0, 100] leave ~90% of draws above the
85
+ # ceiling, so demanding that 60% of examples stay *below* it must fail —
86
+ # and the verdict reports the observed counters.
87
+ def cover_reports_the_observed_rate
88
+ property = lambda do |test_case|
89
+ value = test_case.integer(0, 1000)
90
+ test_case.cover("left below the ceiling", value <= 100, percent: 60)
91
+ end
92
+
93
+ begin
94
+ Zizek.check(property, examples: 200, seed: 1)
95
+ raise "the run should miss the 60% requirement"
96
+ rescue Zizek::FailedCoverage => missed
97
+ missed
98
+ end
99
+ end
100
+
101
+ # A call site registers its label the first time it *runs*. This
102
+ # `sometimes` sits inside a branch the generator can never enter, so the
103
+ # run never even learns the label exists — declaring it in `must_cover:`
104
+ # is what turns that silence into a verdict.
105
+ def must_cover_catches_the_unregistered_label
106
+ property = lambda do |test_case|
107
+ value = test_case.integer(0, 50)
108
+ if value > 100 # unreachable with these bounds
109
+ test_case.sometimes("overflow path", true)
110
+ end
111
+ end
112
+
113
+ begin
114
+ Zizek.check(
115
+ property,
116
+ examples: 100,
117
+ seed: 1,
118
+ must_cover: [Zizek::Coverage.new("overflow path")]
119
+ )
120
+ raise "the run should fail the declared requirement"
121
+ rescue Zizek::FailedCoverage => missed
122
+ missed
123
+ end
124
+ end
125
+ end
126
+
127
+ if $PROGRAM_NAME == __FILE__
128
+ puts "== 1. always: fails and shrinks to the boundary =="
129
+ puts CoverageAssertionsExample.always_shrinks_to_the_boundary.message
130
+ puts "\n== 2. unreachable: shrinks to the simplest reaching input =="
131
+ puts CoverageAssertionsExample.unreachable_finds_the_simplest_path.message
132
+ puts "\n== 3. sometimes: the vacuous pass becomes a failure =="
133
+ puts CoverageAssertionsExample.sometimes_fails_the_vacuous_pass.message
134
+ puts "\n== 4. cover: a required rate, with observed counters =="
135
+ puts CoverageAssertionsExample.cover_reports_the_observed_rate.message
136
+ puts "\n== 5. must_cover: a label whose call site never ran =="
137
+ puts CoverageAssertionsExample.must_cover_catches_the_unregistered_label.message
138
+ end