apollo-smith 0.17.0-beta.0

A GraphQL test case generator.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use crate::description::Description;
use crate::directive::Directive;
use crate::directive::DirectiveLocation;
use crate::name::Name;
use crate::operation::OperationDef;
use crate::selection_set::SelectionSet;
use crate::ty::Ty;
use crate::DocumentBuilder;
use apollo_compiler::ast;
use arbitrary::Result as ArbitraryResult;
use indexmap::IndexMap;
use indexmap::IndexSet;

/// The __fragmentDef type represents a fragment definition
///
/// *FragmentDefinition*:
///     Description? fragment FragmentName TypeCondition Directives? SelectionSet
///
/// Detailed documentation can be found in [GraphQL spec](https://spec.graphql.org/September2025/#FragmentDefinition).
#[derive(Debug, Clone)]
pub struct FragmentDef {
    pub(crate) description: Option<Description>,
    pub(crate) name: Name,
    pub(crate) type_condition: TypeCondition,
    pub(crate) directives: IndexMap<Name, Directive>,
    pub(crate) selection_set: SelectionSet,
}

impl From<FragmentDef> for ast::Definition {
    fn from(x: FragmentDef) -> Self {
        ast::FragmentDefinition {
            description: x.description.map(Into::into),
            name: x.name.into(),
            type_condition: x.type_condition.name.into(),
            directives: Directive::to_ast(x.directives),
            selection_set: x.selection_set.into(),
        }
        .into()
    }
}

impl TryFrom<apollo_parser::cst::FragmentDefinition> for FragmentDef {
    type Error = crate::FromError;

    fn try_from(fragment_def: apollo_parser::cst::FragmentDefinition) -> Result<Self, Self::Error> {
        Ok(Self {
            description: fragment_def.description().map(Description::from),
            name: fragment_def.fragment_name().unwrap().name().unwrap().into(),
            directives: fragment_def
                .directives()
                .map(Directive::convert_directives)
                .transpose()?
                .unwrap_or_default(),
            type_condition: fragment_def.type_condition().unwrap().into(),
            selection_set: fragment_def.selection_set().unwrap().try_into()?,
        })
    }
}

/// The __fragmentSpread type represents a named fragment used in a selection set.
///
/// *FragmentSpread*:
///     ... FragmentName Directives?
///
/// Detailed documentation can be found in [GraphQL spec](https://spec.graphql.org/September2025/#FragmentSpread).
#[derive(Debug, Clone)]
pub struct FragmentSpread {
    pub(crate) name: Name,
    pub(crate) directives: IndexMap<Name, Directive>,
}

impl From<FragmentSpread> for ast::FragmentSpread {
    fn from(x: FragmentSpread) -> Self {
        Self {
            fragment_name: x.name.into(),
            directives: Directive::to_ast(x.directives),
        }
    }
}

impl TryFrom<apollo_parser::cst::FragmentSpread> for FragmentSpread {
    type Error = crate::FromError;

    fn try_from(fragment_spread: apollo_parser::cst::FragmentSpread) -> Result<Self, Self::Error> {
        Ok(Self {
            name: fragment_spread
                .fragment_name()
                .unwrap()
                .name()
                .unwrap()
                .into(),
            directives: fragment_spread
                .directives()
                .map(Directive::convert_directives)
                .transpose()?
                .unwrap_or_default(),
        })
    }
}

/// The __inlineFragment type represents an inline fragment in a selection set that could be used as a field
///
/// *InlineFragment*:
///     ... TypeCondition? Directives? SelectionSet
///
/// Detailed documentation can be found in [GraphQL spec](https://spec.graphql.org/September2025/#sec-Inline-Fragments).
#[derive(Debug, Clone)]
pub struct InlineFragment {
    pub(crate) type_condition: Option<TypeCondition>,
    pub(crate) directives: IndexMap<Name, Directive>,
    pub(crate) selection_set: SelectionSet,
}

impl From<InlineFragment> for ast::InlineFragment {
    fn from(x: InlineFragment) -> Self {
        Self {
            type_condition: x.type_condition.map(|t| t.name.into()),
            directives: Directive::to_ast(x.directives),
            selection_set: x.selection_set.into(),
        }
    }
}

impl TryFrom<apollo_parser::cst::InlineFragment> for InlineFragment {
    type Error = crate::FromError;

    fn try_from(inline_fragment: apollo_parser::cst::InlineFragment) -> Result<Self, Self::Error> {
        Ok(Self {
            directives: inline_fragment
                .directives()
                .map(Directive::convert_directives)
                .transpose()?
                .unwrap_or_default(),
            selection_set: inline_fragment.selection_set().unwrap().try_into()?,
            type_condition: inline_fragment.type_condition().map(TypeCondition::from),
        })
    }
}

/// The __typeCondition type represents where a fragment could be applied
///
/// *TypeCondition*:
///     on NamedType
///
/// Detailed documentation can be found in [GraphQL spec](https://spec.graphql.org/September2025/#TypeCondition).
#[derive(Debug, Clone)]
pub struct TypeCondition {
    name: Name,
}

impl From<apollo_parser::cst::TypeCondition> for TypeCondition {
    fn from(type_condition: apollo_parser::cst::TypeCondition) -> Self {
        Self {
            name: type_condition.named_type().unwrap().name().unwrap().into(),
        }
    }
}

impl DocumentBuilder<'_> {
    /// Create an arbitrary `FragmentDef`
    pub fn fragment_definition(&mut self) -> ArbitraryResult<FragmentDef> {
        // TODO: also choose between enum/scalars/object
        let selected_object_type_name = self.u.choose(&self.object_type_defs)?.name.clone();
        let _ = self.stack_ty(&Ty::Named(selected_object_type_name));
        let name = self.type_name()?;
        let directives = self.directives(DirectiveLocation::FragmentDefinition)?;
        let selection_set = self.selection_set()?;
        let type_condition = self.type_condition()?;
        self.stack.pop();

        Ok(FragmentDef {
            description: None,
            name,
            type_condition,
            directives,
            selection_set,
        })
    }

    /// Create an arbitrary `FragmentSpread`, returns `None` if no fragment definition was previously created
    pub fn fragment_spread(
        &mut self,
        excludes: &mut Vec<Name>,
    ) -> ArbitraryResult<Option<FragmentSpread>> {
        let current_type = self.stack.last().map(|e| e.name().clone());
        let available_fragment: Vec<&FragmentDef> = self
            .fragment_defs
            .iter()
            .filter(|f| {
                !excludes.contains(&f.name)
                    && self.fragment_spread_possible(&f.type_condition.name, current_type.as_ref())
            })
            .collect();

        let name = if available_fragment.is_empty() {
            return Ok(None);
        } else {
            self.u.choose(&available_fragment)?.name.clone()
        };
        let directives = self.directives(DirectiveLocation::FragmentSpread)?;
        excludes.push(name.clone());

        Ok(Some(FragmentSpread { name, directives }))
    }

    /// Create an arbitrary `InlineFragment`
    pub fn inline_fragment(&mut self) -> ArbitraryResult<InlineFragment> {
        let type_condition = self
            .u
            .arbitrary()
            .unwrap_or(false)
            .then(|| self.type_condition())
            .transpose()?;
        let selection_set = self.selection_set()?;
        let directives = self.directives(DirectiveLocation::InlineFragment)?;

        Ok(InlineFragment {
            type_condition,
            directives,
            selection_set,
        })
    }

    /// Whether a fragment with `fragment_type` can be spread inside a
    /// selection set for `current_type`. The two types must share at
    /// least one possible object type.
    ///
    /// See <https://spec.graphql.org/September2025/#sec-Fragment-Spread-Is-Possible>.
    fn fragment_spread_possible(&self, fragment_type: &Name, current_type: Option<&Name>) -> bool {
        let Some(current) = current_type else {
            return true;
        };
        let current_objects = self.possible_object_types(current);
        let fragment_objects = self.possible_object_types(fragment_type);
        current_objects.iter().any(|o| fragment_objects.contains(o))
    }

    /// The set of object types that `type_name` can resolve to at runtime.
    fn possible_object_types(&self, type_name: &Name) -> IndexSet<Name> {
        if self.object_type_defs.iter().any(|o| &o.name == type_name) {
            return IndexSet::from([type_name.clone()]);
        }
        if let Some(u) = self.union_type_defs.iter().find(|u| &u.name == type_name) {
            return u.members.clone();
        }
        // Interface: collect every object whose implements closure includes it
        self.object_type_defs
            .iter()
            .filter(|o| self.implements_graph.closure(&o.name).contains(type_name))
            .map(|o| o.name.clone())
            .collect()
    }

    /// Create an arbitrary `TypeCondition`
    pub fn type_condition(&mut self) -> ArbitraryResult<TypeCondition> {
        let last_element = self.stack.last();
        match last_element {
            Some(last_element) => Ok(TypeCondition {
                name: last_element.name().clone(),
            }),
            None => {
                let named_types: Vec<Ty> = self
                    .list_existing_object_types()
                    .into_iter()
                    .filter(Ty::is_named)
                    .collect();

                Ok(TypeCondition {
                    name: self.choose_named_ty(&named_types)?.name().clone(),
                })
            }
        }
    }
}

/// Compute the set of fragment names reachable from `operations`, walking
/// through `fragments` transitively when one fragment spreads another.
///
/// A fragment is reachable iff some operation spreads it directly, or spreads
/// some other reachable fragment whose chain leads to it. Chains like
/// `A -> B` with no operation referencing A produce no reachable names, even
/// though `A` syntactically references `B`.
pub(crate) fn reachable_fragment_names(
    operations: &[OperationDef],
    fragments: &[FragmentDef],
) -> IndexSet<Name> {
    let mut reachable: IndexSet<Name> = IndexSet::new();
    for op in operations {
        op.selection_set.collect_fragment_spreads(&mut reachable);
    }
    let mut frontier: Vec<Name> = reachable.iter().cloned().collect();
    while let Some(name) = frontier.pop() {
        if let Some(frag) = fragments.iter().find(|f| f.name == name) {
            let mut nested: IndexSet<Name> = IndexSet::new();
            frag.selection_set.collect_fragment_spreads(&mut nested);
            for n in nested {
                if reachable.insert(n.clone()) {
                    frontier.push(n);
                }
            }
        }
    }
    reachable
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse(src: &str) -> (Vec<OperationDef>, Vec<FragmentDef>) {
        let cst = apollo_parser::Parser::new(src).parse();
        assert!(cst.errors().next().is_none(), "parse errors: {src}");
        let mut ops = vec![];
        let mut frags = vec![];
        for def in cst.document().definitions() {
            match def {
                apollo_parser::cst::Definition::OperationDefinition(o) => {
                    ops.push(o.try_into().unwrap())
                }
                apollo_parser::cst::Definition::FragmentDefinition(f) => {
                    frags.push(f.try_into().unwrap())
                }
                _ => panic!("unexpected definition in test input"),
            }
        }
        (ops, frags)
    }

    fn names(items: &[&str]) -> IndexSet<Name> {
        items.iter().map(|s| Name::new(s.to_string())).collect()
    }

    #[test]
    fn no_operations_means_nothing_reachable() {
        let (ops, frags) = parse("fragment A on T { __typename }");
        let result = reachable_fragment_names(&ops, &frags);
        assert!(result.is_empty());
    }

    #[test]
    fn direct_spread_is_reachable() {
        let (ops, frags) = parse(
            "
            query { ...A }
            fragment A on T { __typename }
            ",
        );
        let result = reachable_fragment_names(&ops, &frags);
        assert_eq!(result, names(&["A"]));
    }

    #[test]
    fn transitive_chain_is_reachable() {
        let (ops, frags) = parse(
            "
            query { ...A }
            fragment A on T { ...B }
            fragment B on T { ...C }
            fragment C on T { __typename }
            ",
        );
        let result = reachable_fragment_names(&ops, &frags);
        assert_eq!(result, names(&["A", "B", "C"]));
    }

    #[test]
    fn orphan_chain_is_not_reachable() {
        // A -> B with no operation referencing A: neither retained
        let (ops, frags) = parse(
            "
            fragment A on T { ...B }
            fragment B on T { __typename }
            ",
        );
        let result = reachable_fragment_names(&ops, &frags);
        assert!(result.is_empty());
    }

    #[test]
    fn unreferenced_fragment_among_used_ones_is_pruned() {
        let (ops, frags) = parse(
            "
            query { ...A }
            fragment A on T { __typename }
            fragment B on T { __typename }
            ",
        );
        let result = reachable_fragment_names(&ops, &frags);
        assert_eq!(result, names(&["A"]));
    }

    #[test]
    fn cycle_terminates() {
        // op -> A -> B -> A : both reachable, no infinite loop
        let (ops, frags) = parse(
            "
            query { ...A }
            fragment A on T { ...B }
            fragment B on T { ...A }
            ",
        );
        let result = reachable_fragment_names(&ops, &frags);
        assert_eq!(result, names(&["A", "B"]));
    }
}