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
//! Defines `Node` and `SegmentType` for `Tree`

use std::cmp::Ordering;
use std::collections::HashMap;
use std::borrow::Borrow;
use hyper::{Request, StatusCode};

use http::PercentDecoded;
use router::route::{Route, Delegation};
use router::tree::{SegmentsProcessed, SegmentMapping, Path};
use state::{State, request_id};

/// Indicates the type of segment which is being represented by this Node.
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub enum SegmentType {
    /// Is matched exactly (string equality) to the corresponding segment for incoming request paths.
    ///
    /// Unlike all other `NodeSegmentTypes` values determined to be associated with this segment
    /// within a `Request` path are **not** stored within `State`.
    Static,

    /// Uses the supplied regex to determine match against incoming request paths.
    Constrained {
        /// Regex used to match against a single segment of a request path.
        regex: String,
    },

    /// Matches any corresponding segment for incoming request paths.
    Dynamic,

    /// Matches multiple path segments until the end of the request path or until a child
    /// segment of the above defined types is found.
    Glob,
}

/// A recursive member of `Tree` representative of segment(s) in a routable path.
///
/// Ultimately provides `0..n` `Route` instances which are further evaluated by the `Router` if
/// the `Node` is determined to be the routable end point for a single path through the tree.
///
/// # Examples
///
/// Representing the path `/activate/workflow`.
///
/// ```rust
/// # extern crate gotham;
/// # extern crate hyper;
/// #
/// # use hyper::{Request, Response, Method, StatusCode};
/// #
/// # use gotham::http::PercentDecoded;
/// # use gotham::http::response::create_response;
/// # use gotham::router::request::path::NoopPathExtractor;
/// # use gotham::router::request::query_string::NoopQueryStringExtractor;
/// # use gotham::router::route::{RouteImpl, Extractors, Delegation};
/// # use gotham::router::route::dispatch::{new_pipeline_set, finalize_pipeline_set, DispatcherImpl};
/// # use gotham::state::State;
/// # use gotham::router::route::matcher::MethodOnlyRouteMatcher;
/// # use gotham::router::tree::node::{NodeBuilder, SegmentType};
/// #
/// # fn handler(state: State, _req: Request) -> (State, Response) {
/// #   let res = create_response(&state, StatusCode::Ok, None);
/// #   (state, res)
/// # }
/// #
/// # fn main() {
/// #  let pipeline_set = finalize_pipeline_set(new_pipeline_set());
///   let mut root_node_builder = NodeBuilder::new("/", SegmentType::Static);
///   let mut activate_node_builder = NodeBuilder::new("activate", SegmentType::Static);
///
///   let mut workflow_node = NodeBuilder::new("workflow", SegmentType::Static);
///   let route = {
///       // elided ..
/// #     let methods = vec![Method::Get];
/// #     let matcher = MethodOnlyRouteMatcher::new(methods);
/// #     let dispatcher = Box::new(DispatcherImpl::new(|| Ok(handler), (), pipeline_set));
///       let extractors: Extractors<NoopPathExtractor, NoopQueryStringExtractor> = Extractors::new();
///       let route = RouteImpl::new(matcher, dispatcher, extractors, Delegation::Internal);
///       Box::new(route)
///   };
///   workflow_node.add_route(route);
///
///   activate_node_builder.add_child(workflow_node);
///   root_node_builder.add_child(activate_node_builder);
///
///   let root_node = root_node_builder.finalize();
///   match root_node.traverse(&[&PercentDecoded::new("/").unwrap(),
///                              &PercentDecoded::new("activate").unwrap(),
///                              &PercentDecoded::new("workflow").unwrap()])
///   {
///       Some((path, _leaf, segments_processed, _segment_mapping)) =>  {
///         assert!(path.last().unwrap().is_routable());
///         assert_eq!(segments_processed, 2);
///       }
///       None => panic!(),
///   }
/// # }
/// ```
pub struct Node {
    segment: String,
    segment_type: SegmentType,

    routes: Vec<Box<Route + Send + Sync>>,

    delegating: bool,
    children: Vec<Node>,
}

impl Node {
    /// Provides the segment this `Node` represents.
    pub fn segment(&self) -> &str {
        &self.segment
    }

    /// Provides the type of segment this `Node` represents.
    pub fn segment_type(&self) -> &SegmentType {
        &self.segment_type
    }

    /// Determines if a `Route` instance associated with this `Node` is willing to `Handle` the
    /// `Request`.
    ///
    /// Where multiple `Route` instances could possibly handle the `Request` only the first, ordered
    /// per creation, is invoked.
    ///
    /// Where no `Route` instances will accept the `Request` the resulting Error will be the
    /// erroneous status code provided by the first `Route` instance, ordered per creation.
    ///
    /// In the situation where all these avenues are exhausted an InternalServerError will be
    /// provided.
    pub fn select_route(
        &self,
        state: &State,
        req: &Request,
    ) -> Result<&Box<Route + Send + Sync>, StatusCode> {
        match self.routes.iter().find(|r| r.is_match(state, req).is_ok()) {
            Some(route) => {
                trace!("[{}] found matching route", request_id(state));
                Ok(route)
            }
            None => {
                trace!("[{}] no matching route", request_id(state));
                match self.routes.first() {
                    Some(route) => {
                        trace!("[{}] using error status code from route", request_id(state));
                        Err(route.is_match(state, req).unwrap_err())
                    }
                    None => {
                        trace!("[{}] using generic error status code", request_id(state));
                        Err(StatusCode::InternalServerError)
                    }
                }
            }
        }
    }

    /// True if there is at least one child `Node` present
    pub fn is_parent(&self) -> bool {
        !self.children.is_empty()
    }

    /// True is there is a least one `Route` represented by this `Node`, that is it can act as a
    /// leaf in a single path through the tree.
    pub fn is_routable(&self) -> bool {
        !self.routes.is_empty()
    }

    /// Recursively traverses children attempting to locate a path of nodes which indicate they
    /// match all segments of the `Request` path and with the final `Node` of the path
    /// containing `1..n` `Route` instances for further processing by the `Router`.
    ///
    /// Only the first fully matching path is returned.
    ///
    /// Children are searched in a most to least specific order of contained segment value based on
    /// the `SegmentType` value held by the `Node`:
    ///
    /// 1. Static
    /// 2. Constrained
    /// 3. Dynamic
    /// 4. Glob
    pub fn traverse<'r, 'n>(
        &'n self,
        req_path_segments: &'r [&PercentDecoded],
    ) -> Option<(Path<'n>, &Node, SegmentsProcessed, SegmentMapping<'n, 'r>)> {
        match self.inner_traverse(req_path_segments, vec![]) {
            Some((mut path, leaf, c, sm)) => {
                path.reverse();
                let sm = SegmentMapping { data: sm };
                Some((path, leaf, c, sm))
            }
            None => None,
        }
    }

    #[allow(unknown_lints, type_complexity)]
    fn inner_traverse<'r>(
        &self,
        req_path_segments: &'r [&PercentDecoded],
        mut consumed_segments: Vec<&'r PercentDecoded>,
    ) -> Option<(Vec<&Node>, &Node, SegmentsProcessed, HashMap<&str, Vec<&'r PercentDecoded>>)> {
        match req_path_segments.split_first() {
            Some((x, _)) if self.is_delegating(x) => {
                // A delegated node terminates processing, start building result
                trace!(" found delegator node `{}`", self.segment);

                let mut sm = HashMap::new();
                if self.segment_type != SegmentType::Static {
                    consumed_segments.push(x);
                    sm.insert(self.segment(), consumed_segments);
                };

                Some((vec![self], self, 0, sm))
            }
            Some((x, xs)) if self.is_leaf(x, xs) => {
                trace!(" found leaf node `{}`", self.segment);

                let mut sm = HashMap::new();
                if self.segment_type != SegmentType::Static {
                    consumed_segments.push(x);
                    sm.insert(self.segment(), consumed_segments);
                };

                Some((vec![self], self, 0, sm))
            }
            Some((x, xs)) if self.is_match(x) => {
                trace!(" found node `{}`", self.segment);

                let child = self.children
                    .iter()
                    .filter_map(|c| c.inner_traverse(xs, vec![]))
                    .next();

                match child {
                    Some((mut path, leaf, sp, mut sm)) => {
                        if self.segment_type != SegmentType::Static {
                            consumed_segments.push(x);
                            sm.insert(&self.segment, consumed_segments);
                            path.push(self);
                        }

                        Some((path, leaf, sp + 1, sm))
                    }

                    // If we're in a Glob consume segment and continue
                    // otherwise we've failed to find a suitable way
                    // forward.
                    None if self.segment_type == SegmentType::Glob => {
                        trace!(" continuing with glob match for segment `{}`", self.segment);
                        consumed_segments.push(x);
                        match self.inner_traverse(xs, consumed_segments) {
                            Some((nodes, n, sp, sm)) => Some((nodes, n, sp + 1, sm)),
                            None => None,
                        }
                    }
                    None => None,
                }
            }
            Some(_) => None,
            None => None,
        }
    }

    fn is_delegating(&self, req_path_segment: &PercentDecoded) -> bool {
        self.is_match(req_path_segment) && self.delegating
    }

    fn is_match(&self, req_path_segment: &PercentDecoded) -> bool {
        match self.segment_type {
            SegmentType::Static => self.segment == req_path_segment.val(),
            // TODO #10, address Constrained type
            SegmentType::Constrained { regex: _ } => unimplemented!(),
            SegmentType::Dynamic | SegmentType::Glob => true,
        }
    }

    fn is_leaf(&self, s: &PercentDecoded, rs: &[&PercentDecoded]) -> bool {
        rs.is_empty() && self.is_match(s) && self.is_routable()
    }
}

/// Constructs a `Node` which is sorted and immutable.
pub struct NodeBuilder {
    segment: String,
    segment_type: SegmentType,
    routes: Vec<Box<Route + Send + Sync>>,

    delegating: bool,
    children: Vec<NodeBuilder>,
}

impl NodeBuilder {
    /// Creates new `NodeBuilder` for the given segment.
    pub fn new<S>(segment: S, segment_type: SegmentType) -> Self
    where
        S: Borrow<str>,
    {
        let segment = segment.borrow().to_owned();
        NodeBuilder {
            segment,
            segment_type,
            routes: vec![],
            children: vec![],
            delegating: false,
        }
    }

    /// Access the segment name of the `Node` under construction
    pub fn segment(&self) -> &str {
        &self.segment
    }

    /// Adds a `Route` be evaluated by the `Router` when the built `Node` is acting as a leaf in a
    /// single path through the `Tree`.
    pub fn add_route(&mut self, route: Box<Route + Send + Sync>) {

        if route.delegation() == Delegation::External {
            if !self.routes.is_empty() {
                panic!("Node which is externally delegating must have single Route");
            }

            if !self.children.is_empty() {
                panic!("Node which is externally delegating must not have existing children");
            }

            self.delegating = true;
        };

        trace!(" adding route to `{}`", self.segment());
        self.routes.push(route);
    }

    /// Adds a new child to this sub-tree structure
    pub fn add_child(&mut self, child: NodeBuilder) {
        if self.delegating {
            panic!("Node which is externally delegating must not have existing children")
        }

        trace!(
            " adding child `{}` to `{}`",
            child.segment(),
            self.segment()
        );
        self.children.push(child);
    }

    /// Determines if a child representing the exact segment provided exists.
    pub fn has_child(&self, segment: &str) -> bool {
        self.children
            .iter()
            .find(|n| n.segment == segment)
            .is_some()
    }

    /// Borrow a child that represents the exact segment provided here.
    pub fn borrow_child(&self, segment: &str) -> Option<&NodeBuilder> {
        self.children.iter().find(|n| n.segment == segment)
    }

    /// Mutably borrow a child that represents the exact segment provided here.
    pub fn borrow_mut_child(&mut self, segment: &str) -> Option<&mut NodeBuilder> {
        self.children.iter_mut().find(|n| n.segment == segment)
    }

    /// Finalizes and sorts all internal data, including all children.
    pub fn finalize(mut self) -> Node {
        self.sort();

        let mut children = self.children
            .drain(..)
            .map(|c| c.finalize())
            .collect::<Vec<Node>>();

        children.shrink_to_fit();
        self.routes.shrink_to_fit();

        Node {
            segment: self.segment,
            segment_type: self.segment_type,
            routes: self.routes,
            delegating: self.delegating,
            children,
        }
    }

    // Sorts all children per `PartialEq` and `PartialOrd` implementations.
    //
    // Final ordering of Children is based on most to least specific SegmentType as follows:
    //
    // 1. Static
    // 2. Constrained
    // 3. Dynamic
    // 4. Glob
    fn sort(&mut self) {
        self.children.sort();

        for child in &mut self.children {
            child.sort();
        }
    }
}

impl Ord for NodeBuilder {
    fn cmp(&self, other: &NodeBuilder) -> Ordering {
        (&self.segment_type, &self.segment).cmp(&(&other.segment_type, &other.segment))
    }
}

impl PartialOrd for NodeBuilder {
    fn partial_cmp(&self, other: &NodeBuilder) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for NodeBuilder {
    fn eq(&self, other: &NodeBuilder) -> bool {
        (&self.segment_type, &self.segment) == (&other.segment_type, &other.segment)
    }
}

impl Eq for NodeBuilder {}

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

    use hyper::Method;
    use hyper::{Request, Response};

    use router::route::dispatch::{new_pipeline_set, finalize_pipeline_set, PipelineSet,
                                  DispatcherImpl};
    use router::route::matcher::MethodOnlyRouteMatcher;
    use router::route::{Route, RouteImpl, Extractors};
    use router::request::path::NoopPathExtractor;
    use http::request::path::RequestPathSegments;
    use router::request::query_string::NoopQueryStringExtractor;
    use state::State;

    fn handler(state: State, _req: Request) -> (State, Response) {
        (state, Response::new())
    }

    fn get_route<P>(pipeline_set: PipelineSet<P>) -> Box<Route + Send + Sync>
    where
        P: Send + Sync + 'static,
    {
        let methods = vec![Method::Get];
        let matcher = MethodOnlyRouteMatcher::new(methods);
        let dispatcher = DispatcherImpl::new(|| Ok(handler), (), pipeline_set);
        let extractors: Extractors<NoopPathExtractor, NoopQueryStringExtractor> = Extractors::new();
        let route = RouteImpl::new(
            matcher,
            Box::new(dispatcher),
            extractors,
            Delegation::Internal,
        );
        Box::new(route)
    }

    fn get_delegated_route<P>(pipeline_set: PipelineSet<P>) -> Box<Route + Send + Sync>
    where
        P: Send + Sync + 'static,
    {
        let methods = vec![Method::Get];
        let matcher = MethodOnlyRouteMatcher::new(methods);
        let dispatcher = DispatcherImpl::new(|| Ok(handler), (), pipeline_set);
        let extractors: Extractors<NoopPathExtractor, NoopQueryStringExtractor> = Extractors::new();
        let route = RouteImpl::new(
            matcher,
            Box::new(dispatcher),
            extractors,
            Delegation::External,
        );
        Box::new(route)
    }

    fn test_structure() -> NodeBuilder {
        let mut root: NodeBuilder = NodeBuilder::new("/", SegmentType::Static);
        let pipeline_set = finalize_pipeline_set(new_pipeline_set());

        // Two methods, same path, same handler
        // [Get|Head]: /seg1
        let mut seg1 = NodeBuilder::new("seg1", SegmentType::Static);
        let methods = vec![Method::Get, Method::Head];
        let matcher = MethodOnlyRouteMatcher::new(methods);
        let dispatcher = DispatcherImpl::new(|| Ok(handler), (), pipeline_set.clone());
        let extractors: Extractors<NoopPathExtractor, NoopQueryStringExtractor> = Extractors::new();
        let route = RouteImpl::new(
            matcher,
            Box::new(dispatcher),
            extractors,
            Delegation::Internal,
        );
        seg1.add_route(Box::new(route));
        root.add_child(seg1);

        // Two methods, same path, different handlers
        // Post: /seg2
        let mut seg2 = NodeBuilder::new("seg2", SegmentType::Static);
        let methods = vec![Method::Post];
        let matcher = MethodOnlyRouteMatcher::new(methods);
        let dispatcher = DispatcherImpl::new(|| Ok(handler), (), pipeline_set.clone());
        let extractors: Extractors<NoopPathExtractor, NoopQueryStringExtractor> = Extractors::new();
        let route = RouteImpl::new(
            matcher,
            Box::new(dispatcher),
            extractors,
            Delegation::Internal,
        );
        seg2.add_route(Box::new(route));

        // Patch: /seg2
        let methods = vec![Method::Patch];
        let matcher = MethodOnlyRouteMatcher::new(methods);
        let dispatcher = DispatcherImpl::new(|| Ok(handler), (), pipeline_set.clone());
        let extractors: Extractors<NoopPathExtractor, NoopQueryStringExtractor> = Extractors::new();
        let route = RouteImpl::new(
            matcher,
            Box::new(dispatcher),
            extractors,
            Delegation::Internal,
        );
        seg2.add_route(Box::new(route));
        root.add_child(seg2);

        // Ensure basic traversal
        // Get: /seg3/seg4
        let mut seg3 = NodeBuilder::new("seg3", SegmentType::Static);
        let mut seg4 = NodeBuilder::new("seg4", SegmentType::Static);
        seg4.add_route(get_route(pipeline_set.clone()));
        seg3.add_child(seg4);
        root.add_child(seg3);

        // Ensure traversal will backtrack and find the correct path if it goes down an ultimately
        // invalid branch, in this case seg6 initially being matched by the dynamic handler segdyn1
        // which matches every segment it sees.
        //
        // Get /seg5/:segdyn1/seg7
        // Get /seg5/seg6
        let mut seg5 = NodeBuilder::new("seg5", SegmentType::Static);
        let mut seg6 = NodeBuilder::new("seg6", SegmentType::Static);
        seg6.add_route(get_route(pipeline_set.clone()));

        let mut segdyn1 = NodeBuilder::new(":segdyn1", SegmentType::Dynamic);
        let mut seg7 = NodeBuilder::new("seg7", SegmentType::Static);
        seg7.add_route(get_route(pipeline_set.clone()));

        // Ensure traversal will respect Globs
        let mut seg8 = NodeBuilder::new("seg8", SegmentType::Glob);
        let mut seg9 = NodeBuilder::new("seg9", SegmentType::Static);

        let mut seg10 = NodeBuilder::new(String::from("seg10"), SegmentType::Glob);
        seg10.add_route(get_route(pipeline_set.clone()));

        seg9.add_child(seg10);
        seg8.add_child(seg9);
        root.add_child(seg8);

        segdyn1.add_child(seg7);
        seg5.add_child(segdyn1);
        seg5.add_child(seg6);
        root.add_child(seg5);

        root
    }

    #[test]
    fn manages_children() {
        let root_node_builder = test_structure();

        assert!(root_node_builder.borrow_child("seg1").is_some());
        assert!(root_node_builder.borrow_child("seg2").is_some());
        assert!(root_node_builder.borrow_child("seg0").is_none());
    }

    #[test]
    fn traverses_children() {
        let root = test_structure().finalize();

        // GET /seg3/seg4
        let rs = RequestPathSegments::new("/seg3/seg4");
        match root.traverse(&rs.segments()) {
            Some((path, leaf, sp, _)) => {
                assert_eq!(path.last().unwrap().segment(), "seg4");
                assert_eq!(path.last().unwrap().segment(), leaf.segment());
                assert_eq!(sp, 2);
            }
            None => panic!("traversal should have succeeded here"),
        }

        // GET /seg3/seg4/seg5
        let rs = RequestPathSegments::new("/seg3/seg4/seg5");
        assert!(root.traverse(&rs.segments()).is_none());

        // GET /seg5/seg6
        let rs = RequestPathSegments::new("/seg5/seg6");
        match root.traverse(&rs.segments()) {
            Some((path, _, sp, _)) => {
                assert_eq!(path.last().unwrap().segment(), "seg6");
                assert_eq!(sp, 2);
            }
            None => panic!("traversal should have succeeded here"),
        }

        // GET /seg5/someval/seg7
        let rs = RequestPathSegments::new("/seg5/someval/seg7");
        match root.traverse(&rs.segments()) {
            Some((path, _, sp, _)) => {
                assert_eq!(path.last().unwrap().segment(), "seg7");
                assert_eq!(sp, 3);
            }
            None => panic!("traversal should have succeeded here"),
        }

        // GET /some/path/seg9/another/path
        let rs = RequestPathSegments::new("/some/path/seg9/another/branch");
        match root.traverse(&rs.segments()) {
            Some((path, _, sp, _)) => {
                assert_eq!(path.last().unwrap().segment(), "seg10");
                assert_eq!(sp, 5);
            }
            None => panic!("traversal should have succeeded here"),
        }
    }

    #[test]
    #[should_panic(expected = "Node which is externally delegating must not have existing children")]
    fn panics_when_delegated_node_adds_children() {
        let pipeline_set = finalize_pipeline_set(new_pipeline_set());
        let mut seg1 = NodeBuilder::new("seg1", SegmentType::Static);
        let seg2 = NodeBuilder::new("seg2", SegmentType::Static);

        seg1.add_route(get_delegated_route(pipeline_set));
        seg1.add_child(seg2);
    }

    #[test]
    #[should_panic(expected = "Node which is externally delegating must not have existing children")]
    fn panics_when_node_with_children_is_provided_delegated_route() {
        let pipeline_set = finalize_pipeline_set(new_pipeline_set());
        let mut seg1 = NodeBuilder::new("seg1", SegmentType::Static);
        let seg2 = NodeBuilder::new("seg2", SegmentType::Static);

        seg1.add_child(seg2);
        seg1.add_route(get_delegated_route(pipeline_set));
    }

    #[test]
    #[should_panic(expected = "Node which is externally delegating must have single Route")]
    fn panics_when_node_with_a_route_adds_another() {
        let pipeline_set = finalize_pipeline_set(new_pipeline_set());
        let mut seg1 = NodeBuilder::new("seg1", SegmentType::Static);

        seg1.add_route(get_delegated_route(pipeline_set.clone()));
        seg1.add_route(get_delegated_route(pipeline_set));
    }
}