/
output.rs
1174 lines (1114 loc) · 40.7 KB
/
output.rs
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::BTreeMap;
use std::fmt::{self, Debug, Display};
use std::io;
use crate::error::RoverError;
use crate::utils::table::{self, cell, row};
use ansi_term::{
Colour::{Cyan, Red, Yellow},
Style,
};
use apollo_federation_types::build::BuildHint;
use atty::Stream;
use calm_io::{stderr, stderrln, stdout, stdoutln};
use crossterm::style::Attribute::Underlined;
use rover_client::operations::graph::publish::GraphPublishResponse;
use rover_client::operations::subgraph::delete::SubgraphDeleteResponse;
use rover_client::operations::subgraph::list::SubgraphListResponse;
use rover_client::operations::subgraph::publish::SubgraphPublishResponse;
use rover_client::shared::{CheckResponse, FetchResponse, GraphRef, SdlType};
use rover_client::RoverClientError;
use serde::Serialize;
use serde_json::{json, Value};
use termimad::MadSkin;
/// RoverOutput defines all of the different types of data that are printed
/// to `stdout`. Every one of Rover's commands should return `anyhow::Result<RoverOutput>`
/// If the command needs to output some type of data, it should be structured
/// in this enum, and its print logic should be handled in `RoverOutput::print`
///
/// Not all commands will output machine readable information, and those should
/// return `Ok(RoverOutput::EmptySuccess)`. If a new command is added and it needs to
/// return something that is not described well in this enum, it should be added.
#[derive(Clone, PartialEq, Debug)]
pub enum RoverOutput {
DocsList(BTreeMap<&'static str, &'static str>),
FetchResponse(FetchResponse),
CoreSchema(String),
CompositionResult {
supergraph_sdl: String,
hints: Vec<BuildHint>,
federation_version: Option<String>,
},
SubgraphList(SubgraphListResponse),
CheckResponse(CheckResponse),
GraphPublishResponse {
graph_ref: GraphRef,
publish_response: GraphPublishResponse,
},
SubgraphPublishResponse {
graph_ref: GraphRef,
subgraph: String,
publish_response: SubgraphPublishResponse,
},
SubgraphDeleteResponse {
graph_ref: GraphRef,
subgraph: String,
dry_run: bool,
delete_response: SubgraphDeleteResponse,
},
Profiles(Vec<String>),
Introspection(String),
ErrorExplanation(String),
EmptySuccess,
}
impl RoverOutput {
pub fn print(&self) -> io::Result<()> {
match self {
RoverOutput::DocsList(shortlinks) => {
stderrln!(
"You can open any of these documentation pages by running {}.\n",
Yellow.normal().paint("`rover docs open <slug>`")
)?;
let mut table = table::get_table();
// bc => sets top row to be bold and center
table.add_row(row![bc => "Slug", "Description"]);
for (shortlink_slug, shortlink_description) in shortlinks {
table.add_row(row![shortlink_slug, shortlink_description]);
}
stdoutln!("{}", table)?;
}
RoverOutput::FetchResponse(fetch_response) => {
match fetch_response.sdl.r#type {
SdlType::Graph | SdlType::Subgraph { .. } => print_descriptor("SDL")?,
SdlType::Supergraph => print_descriptor("Supergraph SDL")?,
}
print_content(&fetch_response.sdl.contents)?;
}
RoverOutput::GraphPublishResponse {
graph_ref,
publish_response,
} => {
stderrln!(
"{}#{} Published successfully {}",
graph_ref,
publish_response.api_schema_hash,
publish_response.change_summary
)?;
print_one_line_descriptor("Schema Hash")?;
print_content(&publish_response.api_schema_hash)?;
}
RoverOutput::SubgraphPublishResponse {
graph_ref,
subgraph,
publish_response,
} => {
if publish_response.subgraph_was_created {
stderrln!(
"A new subgraph called '{}' for the '{}' graph was created",
subgraph,
graph_ref
)?;
} else {
stderrln!(
"The '{}' subgraph for the '{}' graph was updated",
subgraph,
graph_ref
)?;
}
if publish_response.supergraph_was_updated {
stderrln!("The gateway for the '{}' graph was updated with a new schema, composed from the updated '{}' subgraph", graph_ref, subgraph)?;
} else {
stderrln!(
"The gateway for the '{}' graph was NOT updated with a new schema",
graph_ref
)?;
}
if let Some(launch_cli_copy) = &publish_response.launch_cli_copy {
stderrln!("{}", launch_cli_copy)?;
}
if !publish_response.build_errors.is_empty() {
let warn_prefix = Red.normal().paint("WARN:");
stderrln!("{} The following build errors occurred:", warn_prefix)?;
stderrln!("{}", &publish_response.build_errors)?;
}
}
RoverOutput::SubgraphDeleteResponse {
graph_ref,
subgraph,
dry_run,
delete_response,
} => {
let warn_prefix = Red.normal().paint("WARN:");
if *dry_run {
if !delete_response.build_errors.is_empty() {
stderrln!(
"{} Deleting the {} subgraph from {} would result in the following build errors:",
warn_prefix,
Cyan.normal().paint(subgraph),
Cyan.normal().paint(graph_ref.to_string()),
)?;
stderrln!("{}", &delete_response.build_errors)?;
stderrln!("{} This is only a prediction. If the graph changes before confirming, these errors could change.", warn_prefix)?;
} else {
stderrln!("{} At the time of checking, there would be no build errors resulting from the deletion of this subgraph.", warn_prefix)?;
stderrln!("{} This is only a prediction. If the graph changes before confirming, there could be build errors.", warn_prefix)?
}
} else {
if delete_response.supergraph_was_updated {
stderrln!(
"The {} subgraph was removed from {}. Remaining subgraphs were composed.",
Cyan.normal().paint(subgraph),
Cyan.normal().paint(graph_ref.to_string()),
)?
} else {
stderrln!(
"{} The gateway for {} was not updated. See errors below.",
warn_prefix,
Cyan.normal().paint(graph_ref.to_string())
)?
}
if !delete_response.build_errors.is_empty() {
stderrln!(
"{} There were build errors as a result of deleting the subgraph:",
warn_prefix,
)?;
stderrln!("{}", &delete_response.build_errors)?;
}
}
}
RoverOutput::CoreSchema(csdl) => {
print_descriptor("CoreSchema")?;
print_content(&csdl)?;
}
RoverOutput::CompositionResult {
supergraph_sdl,
hints,
federation_version: _federation_version,
} => {
let warn_prefix = Cyan.bold().paint("HINT:");
for hint in hints {
stderrln!("{} {}", warn_prefix, hint.message)?;
}
stdoutln!()?;
print_descriptor("CoreSchema")?;
print_content(&supergraph_sdl)?;
}
RoverOutput::SubgraphList(details) => {
let mut table = table::get_table();
// bc => sets top row to be bold and center
table.add_row(row![bc => "Name", "Routing Url", "Last Updated"]);
for subgraph in &details.subgraphs {
// Default to "unspecified" if the url is None or empty.
let url = subgraph
.url
.clone()
.unwrap_or_else(|| "unspecified".to_string());
let url = if url.is_empty() {
"unspecified".to_string()
} else {
url
};
let formatted_updated_at: String = if let Some(dt) = subgraph.updated_at.local {
dt.format("%Y-%m-%d %H:%M:%S %Z").to_string()
} else {
"N/A".to_string()
};
table.add_row(row![subgraph.name, url, formatted_updated_at]);
}
stdoutln!("{}", table)?;
stdoutln!(
"View full details at {}/graph/{}/service-list",
details.root_url,
details.graph_ref.name
)?;
}
RoverOutput::CheckResponse(check_response) => {
print_descriptor("Check Result")?;
print_content(check_response.get_table())?;
}
RoverOutput::Profiles(profiles) => {
if profiles.is_empty() {
stderrln!("No profiles found.")?;
} else {
print_descriptor("Profiles")?;
}
for profile in profiles {
stdoutln!("{}", profile)?;
}
}
RoverOutput::Introspection(introspection_response) => {
print_descriptor("Introspection Response")?;
print_content(&introspection_response)?;
}
RoverOutput::ErrorExplanation(explanation) => {
// underline bolded md
let mut skin = MadSkin::default();
skin.bold.add_attr(Underlined);
stdoutln!("{}", skin.inline(explanation))?;
}
RoverOutput::EmptySuccess => (),
};
Ok(())
}
pub(crate) fn get_internal_data_json(&self) -> Value {
match self {
RoverOutput::DocsList(shortlinks) => {
let mut shortlink_vec = Vec::with_capacity(shortlinks.len());
for (shortlink_slug, shortlink_description) in shortlinks {
shortlink_vec.push(
json!({"slug": shortlink_slug, "description": shortlink_description }),
);
}
json!({ "shortlinks": shortlink_vec })
}
RoverOutput::FetchResponse(fetch_response) => json!(fetch_response),
RoverOutput::CoreSchema(csdl) => json!({ "core_schema": csdl }),
RoverOutput::CompositionResult {
supergraph_sdl,
hints,
federation_version,
} => {
if let Some(federation_version) = federation_version {
json!({
"core_schema": supergraph_sdl,
"hints": hints,
"federation_version": federation_version
})
} else {
json!({
"core_schema": supergraph_sdl,
"hints": hints
})
}
}
RoverOutput::GraphPublishResponse {
graph_ref: _,
publish_response,
} => json!(publish_response),
RoverOutput::SubgraphPublishResponse {
graph_ref: _,
subgraph: _,
publish_response,
} => json!(publish_response),
RoverOutput::SubgraphDeleteResponse {
graph_ref: _,
subgraph: _,
dry_run: _,
delete_response,
} => {
json!(delete_response)
}
RoverOutput::SubgraphList(list_response) => json!(list_response),
RoverOutput::CheckResponse(check_response) => check_response.get_json(),
RoverOutput::Profiles(profiles) => json!({ "profiles": profiles }),
RoverOutput::Introspection(introspection_response) => {
json!({ "introspection_response": introspection_response })
}
RoverOutput::ErrorExplanation(explanation_markdown) => {
json!({ "explanation_markdown": explanation_markdown })
}
RoverOutput::EmptySuccess => json!(null),
}
}
pub(crate) fn get_internal_error_json(&self) -> Value {
let rover_error = match self {
RoverOutput::SubgraphPublishResponse {
graph_ref,
subgraph,
publish_response,
} => {
if !publish_response.build_errors.is_empty() {
Some(RoverError::from(RoverClientError::SubgraphBuildErrors {
subgraph: subgraph.clone(),
graph_ref: graph_ref.clone(),
source: publish_response.build_errors.clone(),
}))
} else {
None
}
}
RoverOutput::SubgraphDeleteResponse {
graph_ref,
subgraph,
dry_run: _,
delete_response,
} => {
if !delete_response.build_errors.is_empty() {
Some(RoverError::from(RoverClientError::SubgraphBuildErrors {
subgraph: subgraph.clone(),
graph_ref: graph_ref.clone(),
source: delete_response.build_errors.clone(),
}))
} else {
None
}
}
_ => None,
};
json!(rover_error)
}
pub(crate) fn get_json_version(&self) -> JsonVersion {
JsonVersion::default()
}
}
fn print_descriptor(descriptor: impl Display) -> io::Result<()> {
if atty::is(Stream::Stdout) {
stderrln!("{}: \n", Style::new().bold().paint(descriptor.to_string()))?;
}
Ok(())
}
fn print_one_line_descriptor(descriptor: impl Display) -> io::Result<()> {
if atty::is(Stream::Stdout) {
stderr!("{}: ", Style::new().bold().paint(descriptor.to_string()))?;
}
Ok(())
}
/// if the user is outputting to a terminal, we want there to be a terminating
/// newline, but we don't want that newline to leak into output that's piped
/// to a file, like from a `graph fetch`
fn print_content(content: impl Display) -> io::Result<()> {
if atty::is(Stream::Stdout) {
stdoutln!("{}", content)
} else {
stdout!("{}", content)
}
}
#[derive(Debug, Clone, Serialize)]
pub(crate) struct JsonOutput {
json_version: JsonVersion,
data: JsonData,
error: Value,
}
impl JsonOutput {
pub(crate) fn success(data: Value, error: Value, json_version: JsonVersion) -> JsonOutput {
JsonOutput {
json_version,
data: JsonData::success(data),
error,
}
}
pub(crate) fn failure(data: Value, error: Value, json_version: JsonVersion) -> JsonOutput {
JsonOutput {
json_version,
data: JsonData::failure(data),
error,
}
}
}
impl fmt::Display for JsonOutput {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", json!(self))
}
}
impl From<RoverError> for JsonOutput {
fn from(error: RoverError) -> Self {
let data_json = error.get_internal_data_json();
let error_json = error.get_internal_error_json();
JsonOutput::failure(data_json, error_json, error.get_json_version())
}
}
impl From<RoverOutput> for JsonOutput {
fn from(output: RoverOutput) -> Self {
let data = output.get_internal_data_json();
let error = output.get_internal_error_json();
JsonOutput::success(data, error, output.get_json_version())
}
}
#[derive(Debug, Clone, Serialize)]
pub(crate) struct JsonData {
#[serde(flatten)]
inner: Value,
success: bool,
}
impl JsonData {
pub(crate) fn success(inner: Value) -> JsonData {
JsonData {
inner,
success: true,
}
}
pub(crate) fn failure(inner: Value) -> JsonData {
JsonData {
inner,
success: false,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub(crate) enum JsonVersion {
#[serde(rename = "1")]
One,
}
impl Default for JsonVersion {
fn default() -> Self {
JsonVersion::One
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use assert_json_diff::assert_json_eq;
use chrono::{DateTime, Local, Utc};
use rover_client::{
operations::{
graph::publish::{ChangeSummary, FieldChanges, TypeChanges},
subgraph::{
delete::SubgraphDeleteResponse,
list::{SubgraphInfo, SubgraphUpdatedAt},
},
},
shared::{ChangeSeverity, SchemaChange, Sdl},
};
use apollo_federation_types::build::{BuildError, BuildErrors};
use crate::anyhow;
use super::*;
#[test]
fn docs_list_json() {
let mut mock_shortlinks = BTreeMap::new();
mock_shortlinks.insert("slug_one", "description_one");
mock_shortlinks.insert("slug_two", "description_two");
let actual_json: JsonOutput = RoverOutput::DocsList(mock_shortlinks).into();
let expected_json = json!(
{
"json_version": "1",
"data": {
"shortlinks": [
{
"slug": "slug_one",
"description": "description_one"
},
{
"slug": "slug_two",
"description": "description_two"
}
],
"success": true
},
"error": null
});
assert_json_eq!(expected_json, actual_json);
}
#[test]
fn fetch_response_json() {
let mock_fetch_response = FetchResponse {
sdl: Sdl {
contents: "sdl contents".to_string(),
r#type: SdlType::Subgraph {
routing_url: Some("http://localhost:8000/graphql".to_string()),
},
},
};
let actual_json: JsonOutput = RoverOutput::FetchResponse(mock_fetch_response).into();
let expected_json = json!(
{
"json_version": "1",
"data": {
"sdl": {
"contents": "sdl contents",
},
"success": true
},
"error": null
});
assert_json_eq!(expected_json, actual_json);
}
#[test]
fn core_schema_json() {
let mock_core_schema = "core schema contents".to_string();
let actual_json: JsonOutput = RoverOutput::CoreSchema(mock_core_schema).into();
let expected_json = json!(
{
"json_version": "1",
"data": {
"core_schema": "core schema contents",
"success": true
},
"error": null
});
assert_json_eq!(expected_json, actual_json);
}
#[test]
fn subgraph_list_json() {
let now_utc: DateTime<Utc> = Utc::now();
let now_local: DateTime<Local> = now_utc.into();
let mock_subgraph_list_response = SubgraphListResponse {
subgraphs: vec![
SubgraphInfo {
name: "subgraph one".to_string(),
url: Some("http://localhost:4001".to_string()),
updated_at: SubgraphUpdatedAt {
local: Some(now_local),
utc: Some(now_utc),
},
},
SubgraphInfo {
name: "subgraph two".to_string(),
url: None,
updated_at: SubgraphUpdatedAt {
local: None,
utc: None,
},
},
],
root_url: "https://studio.apollographql.com/".to_string(),
graph_ref: GraphRef {
name: "graph".to_string(),
variant: "current".to_string(),
},
};
let actual_json: JsonOutput = RoverOutput::SubgraphList(mock_subgraph_list_response).into();
let expected_json = json!(
{
"json_version": "1",
"data": {
"subgraphs": [
{
"name": "subgraph one",
"url": "http://localhost:4001",
"updated_at": {
"local": now_local,
"utc": now_utc
}
},
{
"name": "subgraph two",
"url": null,
"updated_at": {
"local": null,
"utc": null
}
}
],
"success": true
},
"error": null
});
assert_json_eq!(expected_json, actual_json);
}
#[test]
fn subgraph_delete_success_json() {
let mock_subgraph_delete = SubgraphDeleteResponse {
supergraph_was_updated: true,
build_errors: BuildErrors::new(),
};
let actual_json: JsonOutput = RoverOutput::SubgraphDeleteResponse {
delete_response: mock_subgraph_delete,
subgraph: "subgraph".to_string(),
dry_run: false,
graph_ref: GraphRef {
name: "name".to_string(),
variant: "current".to_string(),
},
}
.into();
let expected_json = json!(
{
"json_version": "1",
"data": {
"supergraph_was_updated": true,
"success": true,
},
"error": null
});
assert_json_eq!(expected_json, actual_json);
}
#[test]
fn subgraph_delete_build_errors_json() {
let mock_subgraph_delete = SubgraphDeleteResponse {
supergraph_was_updated: false,
build_errors: vec![
BuildError::composition_error(
Some("AN_ERROR_CODE".to_string()),
Some("[Accounts] -> Things went really wrong".to_string()),
),
BuildError::composition_error(
None,
Some("[Films] -> Something else also went wrong".to_string()),
),
]
.into(),
};
let actual_json: JsonOutput = RoverOutput::SubgraphDeleteResponse {
delete_response: mock_subgraph_delete,
subgraph: "subgraph".to_string(),
dry_run: true,
graph_ref: GraphRef {
name: "name".to_string(),
variant: "current".to_string(),
},
}
.into();
let expected_json = json!(
{
"json_version": "1",
"data": {
"supergraph_was_updated": false,
"success": true,
},
"error": {
"message": "Encountered 2 build errors while trying to build subgraph \"subgraph\" into supergraph \"name@current\".",
"code": "E029",
"details": {
"build_errors": [
{
"message": "[Accounts] -> Things went really wrong",
"code": "AN_ERROR_CODE",
"type": "composition"
},
{
"message": "[Films] -> Something else also went wrong",
"code": null,
"type": "composition"
}
],
}
}
});
assert_json_eq!(expected_json, actual_json);
}
#[test]
fn supergraph_fetch_no_successful_publishes_json() {
let graph_ref = GraphRef {
name: "name".to_string(),
variant: "current".to_string(),
};
let source = BuildErrors::from(vec![
BuildError::composition_error(
Some("AN_ERROR_CODE".to_string()),
Some("[Accounts] -> Things went really wrong".to_string()),
),
BuildError::composition_error(
None,
Some("[Films] -> Something else also went wrong".to_string()),
),
]);
let actual_json: JsonOutput =
RoverError::new(RoverClientError::NoSupergraphBuilds { graph_ref, source }).into();
let expected_json = json!(
{
"json_version": "1",
"data": {
"success": false
},
"error": {
"message": "No supergraph SDL exists for \"name@current\" because its subgraphs failed to build.",
"details": {
"build_errors": [
{
"message": "[Accounts] -> Things went really wrong",
"code": "AN_ERROR_CODE",
"type": "composition",
},
{
"message": "[Films] -> Something else also went wrong",
"code": null,
"type": "composition"
}
]
},
"code": "E027"
}
});
assert_json_eq!(actual_json, expected_json);
}
#[test]
fn check_success_response_json() {
let graph_ref = GraphRef {
name: "name".to_string(),
variant: "current".to_string(),
};
let mock_check_response = CheckResponse::try_new(
Some("https://studio.apollographql.com/graph/my-graph/composition/big-hash?variant=current".to_string()),
10,
vec![
SchemaChange {
code: "SOMETHING_HAPPENED".to_string(),
description: "beeg yoshi".to_string(),
severity: ChangeSeverity::PASS,
},
SchemaChange {
code: "WOW".to_string(),
description: "that was so cool".to_string(),
severity: ChangeSeverity::PASS,
}
],
ChangeSeverity::PASS,
graph_ref,
true,
);
if let Ok(mock_check_response) = mock_check_response {
let actual_json: JsonOutput = RoverOutput::CheckResponse(mock_check_response).into();
let expected_json = json!(
{
"json_version": "1",
"data": {
"target_url": "https://studio.apollographql.com/graph/my-graph/composition/big-hash?variant=current",
"operation_check_count": 10,
"changes": [
{
"code": "SOMETHING_HAPPENED",
"description": "beeg yoshi",
"severity": "PASS"
},
{
"code": "WOW",
"description": "that was so cool",
"severity": "PASS"
},
],
"failure_count": 0,
"success": true,
"core_schema_modified": true,
},
"error": null
});
assert_json_eq!(expected_json, actual_json);
} else {
panic!("The shape of this response should return a CheckResponse")
}
}
#[test]
fn check_failure_response_json() {
let graph_ref = GraphRef {
name: "name".to_string(),
variant: "current".to_string(),
};
let check_response = CheckResponse::try_new(
Some("https://studio.apollographql.com/graph/my-graph/composition/big-hash?variant=current".to_string()),
10,
vec![
SchemaChange {
code: "SOMETHING_HAPPENED".to_string(),
description: "beeg yoshi".to_string(),
severity: ChangeSeverity::FAIL,
},
SchemaChange {
code: "WOW".to_string(),
description: "that was so cool".to_string(),
severity: ChangeSeverity::FAIL,
}
],
ChangeSeverity::FAIL, graph_ref,
false,
);
if let Err(operation_check_failure) = check_response {
let actual_json: JsonOutput = RoverError::new(operation_check_failure).into();
let expected_json = json!(
{
"json_version": "1",
"data": {
"target_url": "https://studio.apollographql.com/graph/my-graph/composition/big-hash?variant=current",
"operation_check_count": 10,
"changes": [
{
"code": "SOMETHING_HAPPENED",
"description": "beeg yoshi",
"severity": "FAIL"
},
{
"code": "WOW",
"description": "that was so cool",
"severity": "FAIL"
},
],
"failure_count": 2,
"success": false,
"core_schema_modified": false,
},
"error": {
"message": "This operation check has encountered 2 schema changes that would break operations from existing client traffic.",
"code": "E030",
}
});
assert_json_eq!(expected_json, actual_json);
} else {
panic!("The shape of this response should return a RoverClientError")
}
}
#[test]
fn graph_publish_response_json() {
let mock_publish_response = GraphPublishResponse {
api_schema_hash: "123456".to_string(),
change_summary: ChangeSummary {
field_changes: FieldChanges {
additions: 2,
removals: 1,
edits: 0,
},
type_changes: TypeChanges {
additions: 4,
removals: 0,
edits: 7,
},
},
};
let actual_json: JsonOutput = RoverOutput::GraphPublishResponse {
graph_ref: GraphRef {
name: "graph".to_string(),
variant: "variant".to_string(),
},
publish_response: mock_publish_response,
}
.into();
let expected_json = json!(
{
"json_version": "1",
"data": {
"api_schema_hash": "123456",
"field_changes": {
"additions": 2,
"removals": 1,
"edits": 0
},
"type_changes": {
"additions": 4,
"removals": 0,
"edits": 7
},
"success": true
},
"error": null
});
assert_json_eq!(expected_json, actual_json);
}
#[test]
fn subgraph_publish_success_response_json() {
let mock_publish_response = SubgraphPublishResponse {
api_schema_hash: Some("123456".to_string()),
build_errors: BuildErrors::new(),
supergraph_was_updated: true,
subgraph_was_created: true,
launch_url: Some("test.com/launchurl".to_string()),
launch_cli_copy: Some(
"Monitor your schema delivery progresson studio: test.com/launchurl".to_string(),
),
};
let actual_json: JsonOutput = RoverOutput::SubgraphPublishResponse {
graph_ref: GraphRef {
name: "graph".to_string(),
variant: "variant".to_string(),
},
subgraph: "subgraph".to_string(),
publish_response: mock_publish_response,
}
.into();
let expected_json = json!(
{
"json_version": "1",
"data": {
"api_schema_hash": "123456",
"supergraph_was_updated": true,
"subgraph_was_created": true,
"success": true,
"launch_url": "test.com/launchurl",
"launch_cli_copy": "Monitor your schema delivery progresson studio: test.com/launchurl",
},
"error": null
});
assert_json_eq!(expected_json, actual_json);
}
#[test]
fn subgraph_publish_failure_response_json() {
let mock_publish_response = SubgraphPublishResponse {
api_schema_hash: None,
build_errors: vec![
BuildError::composition_error(
Some("AN_ERROR_CODE".to_string()),
Some("[Accounts] -> Things went really wrong".to_string()),
),
BuildError::composition_error(
None,
Some("[Films] -> Something else also went wrong".to_string()),
),
]
.into(),
supergraph_was_updated: false,
subgraph_was_created: false,
launch_url: None,
launch_cli_copy: None,
};
let actual_json: JsonOutput = RoverOutput::SubgraphPublishResponse {
graph_ref: GraphRef {
name: "name".to_string(),
variant: "current".to_string(),
},
subgraph: "subgraph".to_string(),
publish_response: mock_publish_response,
}
.into();
let expected_json = json!(
{
"json_version": "1",
"data": {
"api_schema_hash": null,
"subgraph_was_created": false,
"supergraph_was_updated": false,
"success": true,
"launch_url": null,
"launch_cli_copy": null,
},