Debian Codegraph @

lib/testutils/src/proptest.rs

raw
1 // Copyright 2025 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::collections::BTreeMap;
16 use std::fmt::Debug;
17 use std::sync::Arc;
18
19 use itertools::Itertools as _;
20 use jj_lib::backend::CommitId;
21 use jj_lib::merged_tree::MergedTree;
22 use jj_lib::repo::ReadonlyRepo;
23 use jj_lib::repo_path::RepoPath;
24 use jj_lib::repo_path::RepoPathBuf;
25 use jj_lib::repo_path::RepoPathComponent;
26 use proptest::prelude::*;
27 use proptest_derive::Arbitrary;
28 use proptest_state_machine::ReferenceStateMachine;
29
30 use crate::create_tree_with;
31
32 fn arb_file_contents() -> impl Strategy<Value = Vec<u8>> {
33 prop_oneof![
34 // Empty files represent a significant edge case, so we want to increase the likelihood of
35 // empty file contents in subsequent transitions.
36 Just(vec![]),
37 // [0] is the simplest "binary" file and it's included here to increase the likelihood of
38 // identical binary file contents in subsequent transition.
39 Just(vec![0]),
40 // Diffing is line-oriented, so try to generate files with relatively
41 // many newlines.
42 "(\n|[a-z]|\\PC)*".prop_map(|s| s.into_bytes()),
43 // Arbitrary binary contents, not limited to valid UTF-8.
44 proptest::collection::vec(any::<u8>(), 0..32),
45 ]
46 }
47
48 #[derive(Arbitrary, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
49 pub enum DirEntry {
50 File {
51 #[proptest(strategy = "arb_file_contents()")]
52 contents: Vec<u8>,
53 executable: bool,
54 },
55
56 // TODO: Only files are created for now; extend test to include symlinks.
57 #[proptest(skip)]
58 Symlink { target: String },
59
60 // TODO: Only files are created for now; extend test to include submodules.
61 #[proptest(skip)]
62 GitSubmodule { commit: CommitId },
63 }
64
65 fn arb_path_component() -> impl Strategy<Value = String> {
66 // HACK: Forbidding `.` here to avoid `.`/`..` in the path components, which
67 // causes downstream errors.
68 "(a|b|c|d|[\\PC&&[^/.]]+)"
69 }
70
71 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
72 pub enum Transition {
73 /// Create a new [`DirEntry`] at [`path`](Self::SetDirEntry::path).
74 /// - If there is already a file or directory at `path`, it is first
75 /// deleted. (Directories will be recursively deleted.)
76 /// - If [`dir_entry`](Self::SetDirEntry::path) is [`None`], the entry at
77 /// `path` is deleted.
78 SetDirEntry {
79 path: RepoPathBuf,
80 dir_entry: Option<DirEntry>,
81 },
82
83 /// Commit the current working copy. Used by the system under test.
84 Commit,
85 }
86
87 #[derive(Clone, Debug, Default)]
88 pub struct WorkingCopyReferenceStateMachine {
89 entries: BTreeMap<RepoPathBuf, DirEntry>,
90 }
91
92 impl WorkingCopyReferenceStateMachine {
93 /// Check invariants that should be maintained by the test code itself
94 /// (rather than the library code). If these fail, then the test harness is
95 /// buggy.
96 fn check_invariants(&self) {
97 for file_path in self.entries.keys() {
98 for ancestor in file_path.ancestors().skip(1) {
99 assert!(
100 !self.entries.contains_key(ancestor),
101 "file {file_path:?} exists, but {ancestor:?} is not a directory"
102 );
103 }
104 }
105 }
106
107 pub fn paths(&self) -> impl Iterator<Item = &RepoPath> {
108 self.entries.keys().map(AsRef::as_ref)
109 }
110
111 pub fn create_tree(&self, repo: &Arc<ReadonlyRepo>) -> MergedTree {
112 create_tree_with(repo, |builder| {
113 for (path, dir_entry) in &self.entries {
114 match dir_entry.clone() {
115 DirEntry::File {
116 contents,
117 executable,
118 } => {
119 builder.file(path, contents).executable(executable);
120 }
121 DirEntry::Symlink { target } => builder.symlink(path, &target),
122 DirEntry::GitSubmodule { commit } => builder.submodule(path, commit),
123 }
124 }
125 })
126 }
127 }
128
129 impl WorkingCopyReferenceStateMachine {
130 fn arb_extant_directory(&self) -> impl Strategy<Value = RepoPathBuf> + use<> {
131 let extant_directories = if self.entries.is_empty() {
132 vec![RepoPathBuf::root()]
133 } else {
134 self.entries
135 .keys()
136 .flat_map(|file_path| file_path.ancestors().skip(1))
137 .map(|path| path.to_owned())
138 .unique()
139 .collect_vec()
140 };
141
142 proptest::sample::select(extant_directories)
143 }
144
145 fn arb_extant_path(&self) -> impl Strategy<Value = RepoPathBuf> + use<> {
146 proptest::sample::select(
147 self.entries
148 .keys()
149 .flat_map(|file_path| file_path.ancestors())
150 .filter(|path| !path.is_root())
151 .map(|path| path.to_owned())
152 .unique()
153 .collect_vec(),
154 )
155 }
156
157 fn arb_transition_create(&self) -> impl Strategy<Value = Transition> + use<> {
158 (
159 self.arb_extant_directory(),
160 proptest::collection::vec(arb_path_component(), 1..3),
161 any::<DirEntry>(),
162 )
163 .prop_map(|(extant_dir_path, new_path_components, dir_entry)| {
164 let mut path = extant_dir_path;
165 path.extend(
166 new_path_components
167 .iter()
168 .map(|c| RepoPathComponent::new(c).unwrap()),
169 );
170 Transition::SetDirEntry {
171 path,
172 dir_entry: Some(dir_entry),
173 }
174 })
175 }
176
177 fn arb_transition_modify(&self) -> impl Strategy<Value = Transition> + use<> {
178 (self.arb_extant_path(), any::<Option<DirEntry>>()).prop_map(|(path, new_dir_entry)| {
179 Transition::SetDirEntry {
180 path,
181 dir_entry: new_dir_entry,
182 }
183 })
184 }
185 }
186
187 impl ReferenceStateMachine for WorkingCopyReferenceStateMachine {
188 type State = Self;
189
190 type Transition = Transition;
191
192 fn init_state() -> BoxedStrategy<Self::State> {
193 Just(Self::State::default()).boxed()
194 }
195
196 fn transitions(state: &Self::State) -> BoxedStrategy<Self::Transition> {
197 // NOTE: Using `prop_oneof` here instead of `proptest::sample::select`
198 // since it seems to minimize better?
199 if !state.entries.is_empty() {
200 prop_oneof![
201 Just(Transition::Commit),
202 state.arb_transition_create(),
203 state.arb_transition_modify(),
204 ]
205 .boxed()
206 } else {
207 prop_oneof![Just(Transition::Commit), state.arb_transition_create()].boxed()
208 }
209 }
210
211 fn apply(mut state: Self::State, transition: &Self::Transition) -> Self::State {
212 match transition {
213 Transition::Commit => {
214 // Do nothing; this is handled by the system under test.
215 }
216
217 Transition::SetDirEntry { path, dir_entry } => {
218 assert_ne!(path.as_ref(), RepoPath::root());
219 let entries = &mut state.entries;
220 // Remove all entries which are contained within `path` (in case it is a
221 // pre-existing directory).
222 entries.retain(|extant_path, _| !extant_path.starts_with(path));
223 for new_dir in path.ancestors().skip(1) {
224 entries.remove(new_dir);
225 }
226 match dir_entry {
227 Some(dir_entry) => {
228 entries.insert(path.to_owned(), dir_entry.to_owned());
229 }
230 None => {
231 assert!(!entries.contains_key(path));
232 }
233 }
234 }
235 }
236 state.check_invariants();
237 state
238 }
239 }