-
Notifications
You must be signed in to change notification settings - Fork 0
/
dv_unit_tests.py
1964 lines (1634 loc) · 74 KB
/
dv_unit_tests.py
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
from __future__ import print_function
import sys
import os
import random
import unittest
from contextlib import contextmanager
from collections import namedtuple
import argparse
from sim.api import HostEntity, Packet, get_name
from dv_router import DVRouter
from cs168.dv import RoutePacket, Table, TableEntry, DVRouterBase, FOREVER, INFINITY
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(dir_path, "lib"))
from mock import patch
class Route(namedtuple("RouteAd", ["dst", "latency"])):
"""Helper class for checking route advertisements."""
def __repr__(self):
return "RouteAd(dst={}, latency={})".format(
get_name(self.dst), self.latency
)
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def assertItemsEqual(actual, expected, message):
actual.sort()
expected.sort()
union = set(actual).union(set(expected))
failure = False
for item in union:
if not item in expected:
message += "\n"+"Extraneous Value: "+str(item)
failure = True
intersection = set(actual).intersection(set(expected))
for item in expected:
if not item in intersection:
message += "\n"+"Missing Value: "+str(item)
failure = True
if failure:
assert True == False, message
class DataPacket(Packet):
"""A packet with data."""
def __init__(self, dst, src, name):
super(DataPacket, self).__init__(dst=dst, src=src)
self.name = name
def __repr__(self):
return "<Packet name=%s %s->%s>" % (
self.name, get_name(self.src), get_name(self.dst)
)
class TestDVRouterBase(unittest.TestCase):
"""Base class for DVRouter tests."""
def _set_up(self, poison_reverse, poison_expired, poison_on_link_down, split_horizon, send_on_link_up, triggered=False):
# Raise an error if time.time() is called.
call_time_error = AssertionError(
"DO NOT call time.time() for timestamps; "
"call api.current_time() instead"
)
call_time_patcher = patch("time.time", side_effect=call_time_error)
call_time_patcher.start()
self.addCleanup(call_time_patcher.stop)
# Simulate time.
self._current_time = 50
current_time_patch = patch("sim.api.current_time",
side_effect=lambda: self._current_time)
current_time_patch.start()
self.addCleanup(current_time_patch.stop)
DVRouter.POISON_REVERSE = poison_reverse
DVRouter.POISON_EXPIRED = poison_expired
DVRouter.POISON_ON_LINK_DOWN = poison_on_link_down
DVRouter.SPLIT_HORIZON = split_horizon
DVRouter.SEND_ON_LINK_UP = send_on_link_up
#DVRouter.TRIGGERED = triggered
DVRouter.DEFAULT_TIMER_INTERVAL = 5
with patch("dv_router.DVRouter.start_timer") as start_timer:
self.router = DVRouter()
assert not (DVRouter.SPLIT_HORIZON and DVRouter.POISON_REVERSE), "Split horizon and poison reverse can't be on"
start_timer.assert_called_once() # Make sure start_timer is called.
self.assertEqual(self.router.POISON_REVERSE, poison_reverse,
"POISON_REVERSE flag doesn't match")
self.assertEqual(self.router.POISON_EXPIRED, poison_expired,
"POISON_EXPIRED flag doesn't match")
self.assertEqual(self.router.POISON_ON_LINK_DOWN, poison_on_link_down,
"POISON_ON_LINK_DOWN flag doesn't match")
self.assertEqual(self.router.SPLIT_HORIZON, split_horizon,
"SPLIT_HORIZON flag doesn't match")
self.assertEqual(self.router.SEND_ON_LINK_UP, send_on_link_up,
"SEND_ON_LINK_UP flag doesn't match")
def _set_current_time(self, new_time):
"""Sets current time. Time must only go forward."""
self.assertGreaterEqual(
new_time, self._current_time,
"BUG: turning time back from {} to {}".format(
self._current_time, new_time)
)
self._current_time = new_time
@contextmanager
def _patch_send(self, all_ports):
"""
Mock send function that captures all packets sent (for `self.router`).
Yields a dict mapping port => list of packets sent to the port.
:param all_ports: all ports that are up for the router.
"""
# Type check and validate `all_ports`, just to be sure.
_all_ports = set()
for port in all_ports:
self.assertIsInstance(port, int, "invalid port %d" % port)
self.assertNotIn(port, _all_ports, "duplicate port %d" % port)
_all_ports.add(port)
del all_ports
sent_packets = {port: [] for port in _all_ports}
def _send(packet, port=None, flood=None):
"""Emulates `send`."""
self.assertIsInstance(packet, Packet,
"{} is not a Packet".format(packet))
if packet.src is None:
packet.src = self.router
if port is None:
ports = set()
elif isinstance(port, int):
ports = {port}
else:
# `port` had better be iterable.
ports = set(port)
del port
if flood:
# Take the inverse.
ports = _all_ports - ports
for port in ports:
self.assertIn(port, sent_packets,
"invalid port number {}".format(port))
sent_packets[port].append(packet)
with patch.object(self.router, "send", side_effect=_send):
yield sent_packets
@contextmanager
def _ensure_no_send(self, all_ports):
"""Ensures that no packet is sent."""
with self._patch_send(all_ports) as sent_packets:
yield
for port, packets in sent_packets.items():
self.assertListEqual(
packets, [], "unexpected packet(s) sent to port {}: {}".format(
port, packets
))
@contextmanager
def _patch_send_routes(self, all_ports, allow_dup=False):
"""
Mock send function that captures route advertisements sent.
Yields a nested dict mapping port => dst => Route, denoting the
route advertisement sent to port for destination dst.
Fails if any packet sent is not a route advertisement. Unless
`allow_dup` is set, fails if duplicate route advertisements have
been sent.
Fails if multiple route ads are sent for the same destination.
:param all_ports: all ports that are up for the router.
"""
advertised_routes = {port: {} for port in all_ports}
with self._patch_send(all_ports) as sent_packets:
yield advertised_routes
for port, packets in sent_packets.items():
for packet in packets:
self.assertIsInstance(
packet, RoutePacket,
"sent packet {} isn't route advertisement".format(packet)
)
dst, lat = packet.destination, packet.latency
route = Route(dst, lat)
old = advertised_routes[port].get(dst)
if old is None:
advertised_routes[port][dst] = route
else:
self.assertEqual(
old.dst, dst, "BUG: route ad dst differ"
)
self.assertEqual(
old, route,
"duplicate route advertisement for HOST {} sent to "
"PORT {} with different latency: old={} new={}".format(
get_name(dst), port, old.latency, lat
)
)
if not allow_dup:
self.fail(
"duplicate route advertisement for HOST {} sent "
"to PORT {} (latency={})".format(
get_name(dst), port, lat
)
)
def _add_test_routes_raw(self):
"""
Adds some simple test table entries.
LINKS: TABLE:
+------+---------+ +------+------+---------+
| Port | Latency | | Dest | Port | Latency |
+------+---------+ +------+------+---------+
| 1 | 5 | | h1 | 1 | 8 |
| 2 | 1 | | h2 | 3 | 5 |
| 3 | 3 | +------+------+---------+
+------+---------+
"""
h1 = _create_host("h1")
h2 = _create_host("h2")
self.h1 = h1
self.h2 = h2
self.router.handle_link_up(port=1, latency=5)
self.router.handle_link_up(port=2, latency=1)
self.router.handle_link_up(port=3, latency=3)
self.router.table.update({
h1: TableEntry(dst=h1, port=1, latency=8, expire_time=115),
h2: TableEntry(dst=h2, port=3, latency=5, expire_time=109),
})
self._set_current_time(100)
def _add_test_routes_proper(self):
"""
Adds some simple test routes.
Configuration after all the links and routes have been added:
LINKS: TABLE:
+------+---------+ +------+------+---------+
| Port | Latency | | Dest | Port | Latency |
+------+---------+ +------+------+---------+
| 1 | 5 | | h1 | 1 | 8 |
| 2 | 1 | | h2 | 3 | 5 |
| 3 | 3 | +------+------+---------+
| 10 | 1 |
+------+---------+
"""
h1 = _create_host("h1")
h2 = _create_host("h2")
self.h1 = h1
self.h2 = h2
self.h3 = _create_host("h3")
self.router.handle_link_up(port=1, latency=5)
self.router.handle_link_up(port=2, latency=1)
self.router.handle_link_up(port=3, latency=3)
self.router.handle_link_up(port=10, latency=1)
self._set_current_time(94)
self.router.handle_route_advertisement(
h1, port=1, route_latency=3)
self._set_current_time(96)
self.router.handle_route_advertisement(
h2, port=1, route_latency=6)
self._set_current_time(98)
self.router.handle_route_advertisement(
h1, port=3, route_latency=10)
self._set_current_time(100)
self.router.handle_route_advertisement(
h2, port=3, route_latency=2)
self._assert_table_equal({
h1: TableEntry(dst=h1, port=1, latency=8, expire_time=94+self.router.ROUTE_TTL),
h2: TableEntry(dst=h2, port=3, latency=5, expire_time=100+self.router.ROUTE_TTL),
})
def _compute_dict_diff(self, d, expected, singular, plural):
message = ""
failed = False
def pe(count): return _pluralize(count, singular, plural)
extra = set(d.keys()) - set(expected.keys())
if extra:
failed = True
message += "\nEXTRANEOUS %s:\n" % pe(len(extra))
for k in sorted(extra):
message += "\t{}\n".format(d[k])
del extra
missing = set(expected.keys()) - set(d.keys())
if missing:
failed = True
message += "\nMISSING %s:\n" % pe(len(missing))
for k in sorted(missing):
message += "\t{}\n".format(expected[k])
del missing
incorrect = {k for k in set(d.keys()) & set(expected.keys())
if d[k] != expected[k]}
if incorrect:
failed = True
message += "\nINCORRECT %s:\n" % pe(len(incorrect))
for k in sorted(incorrect):
message += "\n"
message += "\tExpected: {}\n".format(expected[k])
message += "\tActual: {}\n".format(d[k])
if failed:
self.assertTrue(message, "BUG: error message should not be empty")
return message
else:
return None
def _assert_table_equal(self, expected):
"""Asserts that the router's forwarding table matches expected."""
self.assertIsInstance(expected, dict, "BUG: expected is not a dict")
t = self.router.table
self.assertIsInstance(t, Table,
"{} is not a Table".format(t))
failure = self._compute_dict_diff(
t, expected,
singular="table entry",
plural="table entries"
)
if failure:
self.fail(failure)
else:
if len(expected) > 0 and not "TableEntry" in str((type(expected[list(expected.keys())[0]]))):
self.assertDictEqual(t, expected, "BUG: dicts should be equal")
def _assert_packets_sent(self, sent, expected):
"""Asserts that packets sent match expected."""
assertItemsEqual(
list(sent.keys()), list(expected.keys()),
"BUG: ports mismatch for sent packets"
)
def dps(ps): return str(ps) if ps else "(none)"
failed = False
message = ""
for port in sorted(sent.keys()):
self.assertIsInstance(port, int,
"BUG: port {} is not a int".format(port))
self.assertIsInstance(sent[port], list,
"BUG: {} is not a list".format(sent[port]))
self.assertIsInstance(
expected[port], list,
"BUG: {} is not a list".format(expected[port])
)
if sent[port] != expected[port]:
failed = True
message += "\n\nMISMATCH detected for packets sent to PORT %d:\n" % port
message += "\tEXPECTED packets sent: %s\n" % dps(
expected[port])
message += "\tACTUAL packets sent: %s\n" % dps(sent[port])
if failed:
self.assertTrue(message, "BUG: there should be an error message")
self.fail(message)
else:
self.assertDictEqual(sent, expected, "BUG: dicts should be equal")
def _assert_route_ads_sent(self, sent, expected_sets):
"""
Asserts that route advertisements sent match expected.
:param expected: dict mapping port => set of Route objects.
"""
assertItemsEqual(
list(sent.keys()), list(expected_sets.keys()),
"BUG: ports mismatch for sent route advertisements"
)
for routes in expected_sets.values():
self.assertIsInstance(routes, set, "BUG: routes is not a set")
self.assertEqual(
len(routes), len(set(r.dst for r in routes)),
"BUG: duplicate destination in expected_sets"
)
expected = {
port: {r.dst: r for r in routes}
for port, routes in expected_sets.items()
}
failed = False
message = ""
for port in sorted(sent.keys()):
self.assertIsInstance(port, int,
"BUG: port {} is not a int".format(port))
self.assertIsInstance(sent[port], dict,
"BUG: {} is not a dict".format(sent[port]))
self.assertIsInstance(
expected[port], dict,
"BUG: {} is not a list".format(expected[port])
)
failure = self._compute_dict_diff(
sent[port], expected[port],
singular="route advertisement",
plural="route advertisements"
)
if failure:
failed = True
message += "\n\nMISMATCH detected for route advertisements sent to port %d:" % port
message += _indent(failure)
if failed:
self.assertTrue(message, "BUG: there should be an error message")
self.fail(message)
else:
self.assertDictEqual(sent, expected, "BUG: dicts should be equal")
def _assert_route_ads_sent_passed(self, sent, expected_sets):
"""
Asserts that route advertisements sent match expected.
:param expected: dict mapping port => set of Route objects.
"""
assertItemsEqual(
list(sent.keys()), list(expected_sets.keys()),
"BUG: ports mismatch for sent route advertisements"
)
for routes in expected_sets.values():
self.assertIsInstance(routes, set, "BUG: routes is not a set")
self.assertEqual(
len(routes), len(set(r.dst for r in routes)),
"BUG: duplicate destination in expected_sets"
)
expected = {
port: {r.dst: r for r in routes}
for port, routes in expected_sets.items()
}
failed = False
message = ""
for port in sorted(sent.keys()):
self.assertIsInstance(port, int,
"BUG: port {} is not a int".format(port))
self.assertIsInstance(sent[port], dict,
"BUG: {} is not a dict".format(sent[port]))
self.assertIsInstance(
expected[port], dict,
"BUG: {} is not a list".format(expected[port])
)
failure = self._compute_dict_diff(
sent[port], expected[port],
singular="route advertisement",
plural="route advertisements"
)
if failure:
failed = True
message += "\n\nMISMATCH detected for route advertisements sent to port %d:" % port
message += _indent(failure)
if failed:
return False
else:
return True
def _gather_timer_ads(self, ports, advance):
"""
Forwards time by `advance` seconds and calls timer.
Returns route ads to each port.
"""
with self._patch_send_routes(all_ports=ports) as ads:
old_time = self._current_time
self._set_current_time(old_time + advance)
self.router.handle_timer()
return ads
class TestStarterCode(TestDVRouterBase):
"""
Tests for the starter code. They DO NOT count as part of your grade.
These tests should pass without any modifications on your part. If these
tests fail, make sure you didn't change the starter code!
"""
def setUp(self):
self._set_up(poison_reverse=False, poison_expired=False,
poison_on_link_down=False, split_horizon=False, send_on_link_up=False)
def test_init(self):
"""Tests DVRouter initialization."""
# Initially, all tables should be empty.
self.assertDictEqual(
#self.router.link_latency, {},
self.router.ports.get_underlying_dict(), {},
"link_latency isn't empty: {}".format(self.router.ports.get_underlying_dict())
)
self._assert_table_equal({})
def test_handle_link_up(self):
"""Tests handler for link up."""
# Add a link.
self.router.handle_link_up(port=1234, latency=42)
ex_link_lat = {1234: 42} # Expected link latency table.
self.assertDictEqual(self.router.ports.get_underlying_dict(), ex_link_lat)
# Add a second link!
self.router.handle_link_up(port=1, latency=0.1)
ex_link_lat.update({1: 0.1})
self.assertDictEqual(self.router.ports.get_underlying_dict(), ex_link_lat)
def test_handle_link_down(self):
"""Tests handler for link down."""
# Add a link.
self.router.handle_link_up(port=1234, latency=42)
ex_link_lat = {1234: 42} # Expected link latency table.
self.assertDictEqual(self.router.ports.get_underlying_dict(), ex_link_lat)
# Add a second link!
self.router.handle_link_up(port=1, latency=0.1)
ex_link_lat.update({1: 0.1})
self.assertDictEqual(self.router.ports.get_underlying_dict(), ex_link_lat)
# Remove second link.
self.router.handle_link_down(port=1)
del(ex_link_lat[1])
self.assertDictEqual(self.router.ports.get_underlying_dict(), ex_link_lat)
class TestStaticRoutes(TestDVRouterBase):
"""
Tests for adding static routes.
Each unit test starts off with an empty topology.
"""
def setUp(self):
self._set_up(poison_reverse=False, poison_expired=False,
poison_on_link_down=False, split_horizon=False, send_on_link_up=False)
def test_add_static_route(self):
"""Tests adding static routes."""
DIRECT_LATENCY = 0.1
host1 = _create_host("host1")
# Add the first host.
self.router.handle_link_up(port=1234, latency=DIRECT_LATENCY)
self.router.add_static_route(host1, port=1234)
expected_rts = { # Expected table.
host1: TableEntry(
dst=host1, port=1234,
latency=DIRECT_LATENCY, # No latency after the first hop.
expire_time=FOREVER,
)
}
self._assert_table_equal(expected_rts)
# Add a second host!
host2 = _create_host("host2")
self.router.handle_link_up(port=1, latency=DIRECT_LATENCY)
self.router.add_static_route(host2, port=1)
expected_rts.update({ # New table.
host2: TableEntry(
dst=host2, port=1,
latency=DIRECT_LATENCY, expire_time=FOREVER,
)
})
self._assert_table_equal(expected_rts)
class TestForwarding(TestDVRouterBase):
"""
Tests for forwarding data-plane packets.
See docstring for the _add_test_routes_raw() method for initial link,
peer table, and forwarding table configurations. The current time starts
off at 100.
"""
def setUp(self):
self._set_up(poison_reverse=False, poison_expired=False,
poison_on_link_down=False, split_horizon=False, send_on_link_up=False)
self._add_test_routes_raw()
def test_forward(self):
"""Ensures that packets are forwarded according to forwarding table."""
hs = _create_host("hs")
with self._patch_send(all_ports={1, 2, 3}) as sent_packets:
packet1 = DataPacket(dst=self.h2, src=hs, name="foo")
self.router.handle_data_packet(packet1, in_port=2)
self._assert_packets_sent(sent_packets, {
1: [], 2: [], 3: [packet1],
})
# Send another packet.
with self._patch_send(all_ports={1, 2, 3}) as sent_packets:
packet2 = DataPacket(dst=self.h1, src=hs, name="bar")
self.router.handle_data_packet(packet2, in_port=3)
self._assert_packets_sent(sent_packets, {
1: [packet2], 2: [], 3: [],
})
def test_drop(self):
"""Ensures that router drops packet if no route is known."""
packet = Packet(dst=_create_host("hx"), src=_create_host("hy"))
with self._ensure_no_send(all_ports={1, 2, 3}):
self.router.handle_data_packet(packet, in_port=2)
def test_infinity(self):
"""Ensures packets for destinations of latency infinity are dropped."""
h3 = _create_host("h3")
self.router.table.update({
h3: TableEntry(
dst=h3, port=1,
latency=INFINITY, expire_time=FOREVER,
)
})
packet = Packet(dst=h3, src=_create_host("hz"))
with self._ensure_no_send(all_ports={1, 2, 3}):
self.router.handle_data_packet(packet, in_port=3)
def test_bigger_than_infinity(self):
"""Ensures packets for destinations of latency larger than infinity are dropped."""
h3 = _create_host("h3")
self.router.table.update({
h3: TableEntry(
dst=h3, port=1,
latency=INFINITY+1, expire_time=FOREVER,
)
})
packet = Packet(dst=h3, src=_create_host("hz"))
with self._ensure_no_send(all_ports={1, 2, 3}):
self.router.handle_data_packet(packet, in_port=3)
class TestAdvertise(TestDVRouterBase):
"""
Tests for advertising routes on timer.
See docstring for the _add_test_routes_raw() method for initial link,
peer table, and forwarding table configurations. The current time starts
off at 100.
"""
def setUp(self):
self._set_up(poison_reverse=False, poison_expired=False,
poison_on_link_down=False, split_horizon=False, send_on_link_up=False)
self._add_test_routes_raw()
def test_send_routes(self):
"""Ensures that send_routes(force=True) advertises correctly."""
# Routes advertised out of each port.
all_ports = {1, 2, 3}
with self._patch_send_routes(all_ports) as advertised_routes:
self.router.send_routes(force=True, single_port=None)
self._assert_route_ads_sent(
advertised_routes, {
1: {Route(self.h1, 8), Route(self.h2, 5)},
2: {Route(self.h1, 8), Route(self.h2, 5)},
3: {Route(self.h1, 8), Route(self.h2, 5)}
}
)
class TestHandleAdvertisement(TestDVRouterBase):
"""
Tests for route advertisement handling.
See docstring for the _add_test_routes_raw() method for initial link,
peer table, and forwarding table configurations. The current time starts
off at 102.
"""
def setUp(self):
self._set_up(poison_reverse=False, poison_expired=False,
poison_on_link_down=False, split_horizon=False, send_on_link_up=False)
self.h1 = _create_host("host1")
self.h2 = _create_host("host2")
self.h3 = _create_host("host3")
def test_single_neighbor(self):
"""Merging updates -- when your router only has one neighbor."""
self.router.handle_link_up(port=1, latency=5.5)
h1, h2, h3 = self.h1, self.h2, self.h3
self.router.handle_route_advertisement(
h1, port=1, route_latency=2)
self.router.handle_route_advertisement(
h2, port=1, route_latency=0)
self.router.handle_route_advertisement(
h3, port=1, route_latency=0.5)
self._assert_table_equal({
h1: TableEntry(dst=h1, port=1, latency=7.5, expire_time=65),
h2: TableEntry(dst=h2, port=1, latency=5.5, expire_time=65),
h3: TableEntry(dst=h3, port=1, latency=6, expire_time=65),
})
def test_multiple_neighbors(self):
"""Merging multiple peer updates."""
self.router.handle_link_up(port=1, latency=5.5)
self.router.handle_link_up(port=3, latency=2)
h1, h2, h3 = self.h1, self.h2, self.h3
self.router.handle_route_advertisement(
h1, port=1, route_latency=1)
self.router.handle_route_advertisement(
h2, port=1, route_latency=2)
self.router.handle_route_advertisement(
h3, port=1, route_latency=3)
self.router.handle_route_advertisement(
h2, port=3, route_latency=5)
self.router.handle_route_advertisement(
h3, port=3, route_latency=7)
self._assert_table_equal({
h1: TableEntry(dst=h1, port=1, latency=1 + 5.5, expire_time=65),
h2: TableEntry(dst=h2, port=3, latency=2 + 5, expire_time=65),
h3: TableEntry(dst=h3, port=1, latency=3 + 5.5, expire_time=65),
})
def test_ties(self):
"""Ensures implementation can break ties (choosing the current route)."""
self.router.handle_link_up(port=1, latency=5)
self.router.handle_link_up(port=3, latency=2)
h1, h2 = self.h1, self.h2
self.router.handle_route_advertisement(
h1, port=1, route_latency=1)
self.router.handle_route_advertisement(
h2, port=1, route_latency=2)
self.router.handle_route_advertisement(
h1, port=3, route_latency=4)
self.router.handle_route_advertisement(
h2, port=3, route_latency=5)
self._assert_table_equal({
h1: TableEntry(dst=h1, port=1, latency=1 + 5, expire_time=65),
h2: TableEntry(dst=h2, port=1, latency=2 + 5, expire_time=65),
})
def test_update_same_port_shorter(self):
"""Ensures forwarding table is updated after route change (same port, shorter route)."""
self.test_multiple_neighbors()
h1, h2, h3 = self.h1, self.h2, self.h3
self.router.handle_route_advertisement(
h2, port=3, route_latency=1)
self._assert_table_equal({
h1: TableEntry(dst=h1, port=1, latency=1 + 5.5, expire_time=65),
h2: TableEntry(dst=h2, port=3, latency=2 + 1, expire_time=65),
h3: TableEntry(dst=h3, port=1, latency=3 + 5.5, expire_time=65),
})
def test_update_same_port_longer(self):
"""Ensures forwarding table is updated after route change (same port, longer route)."""
self.test_multiple_neighbors()
h1, h2, h3 = self.h1, self.h2, self.h3
self.router.handle_route_advertisement(
h2, port=3, route_latency=5.25)
self._assert_table_equal({
h1: TableEntry(dst=h1, port=1, latency=1 + 5.5, expire_time=65),
h2: TableEntry(dst=h2, port=3, latency=2 + 5.25, expire_time=65),
h3: TableEntry(dst=h3, port=1, latency=3 + 5.5, expire_time=65),
})
def test_update_alternate_port_shorter(self):
"""Ensures forwarding table is updated after a route change (another port, shorter route)."""
self.test_multiple_neighbors()
h1, h2, h3 = self.h1, self.h2, self.h3
self.router.handle_route_advertisement(
h2, port=1, route_latency=1)
self._assert_table_equal({
h1: TableEntry(dst=h1, port=1, latency=1 + 5.5, expire_time=65),
h2: TableEntry(dst=h2, port=1, latency=1 + 5.5, expire_time=65),
h3: TableEntry(dst=h3, port=1, latency=3 + 5.5, expire_time=65),
})
def test_update_alternate_port_longer(self):
"""Ensures forwarding table is not updated after a route change (another port, longer route)."""
self.test_multiple_neighbors()
h1, h2, h3 = self.h1, self.h2, self.h3
self.router.handle_route_advertisement(
h2, port=1, route_latency=6)
self._assert_table_equal({
h1: TableEntry(dst=h1, port=1, latency=1 + 5.5, expire_time=65),
h2: TableEntry(dst=h2, port=3, latency=2 + 5, expire_time=65),
h3: TableEntry(dst=h3, port=1, latency=3 + 5.5, expire_time=65),
})
def test_update_alternate_port_longer_same_port(self):
"""Ensures forwarding table is updated after a route change (same port, longer route)."""
self.test_multiple_neighbors()
h1, h2, h3 = self.h1, self.h2, self.h3
self.router.handle_route_advertisement(
h2, port=3, route_latency=6)
self._assert_table_equal({
h1: TableEntry(dst=h1, port=1, latency=1 + 5.5, expire_time=65),
h2: TableEntry(dst=h2, port=3, latency=2 + 6, expire_time=65),
h3: TableEntry(dst=h3, port=1, latency=3 + 5.5, expire_time=65),
})
class TestRemoveRoutes(TestDVRouterBase):
"""
Tests for removing routes on timer and link down.
See docstring for the _add_test_routes_proper() method for initial link,
peer table, and forwarding table configurations. The current time starts
off at 100.
"""
def setUp(self):
self._set_up(poison_reverse=False, poison_expired=False,
poison_on_link_down=False, split_horizon=False, send_on_link_up=False)
self._add_test_routes_proper()
def test_expire_routes_none(self):
"""No routes expire."""
h1, h2 = self.h1, self.h2
# Current time is 100, so no routes expire.
self.router.expire_routes()
self._assert_table_equal({
h1: TableEntry(dst=h1, port=1, latency=8, expire_time=109),
h2: TableEntry(dst=h2, port=3, latency=5, expire_time=115),
})
def test_expire_routes_forever(self):
"""Routes with expire_time=FOREVER shouldn't expire."""
h3 = _create_host("h3")
self.router.add_static_route(h3, port=10)
actual = self.router.table[h3].expire_time
self.assertEqual(
actual, FOREVER,
"route for host h3 through port 10 should have latency=FOREVER, "
"instead got latency={}".format(actual)
)
self._set_current_time(10000)
self.router.expire_routes()
self._assert_table_equal({
h3: TableEntry(dst=h3, port=10, latency=1, expire_time=FOREVER),
})
def test_expire_routes_some(self):
"""Some of the routes for a destination expire."""
h1, h2 = self.h1, self.h2
self._set_current_time(110)
self.router.expire_routes()
self._assert_table_equal({
h2: TableEntry(dst=h2, port=3, latency=5, expire_time=115),
})
def test_expire_routes_more(self):
"""Expire all routes for a destination."""
h1, h2 = self.h1, self.h2
packet = Packet(dst=h1, src=h2)
with self._patch_send(all_ports={1, 2, 3, 10}) as sent_packets:
self.router.handle_data_packet(packet, in_port=10)
self._assert_packets_sent(
sent_packets, {1: [packet], 2: [], 3: [], 10: []}
)
self._set_current_time(114)
self.router.expire_routes()
expected = TableEntry(dst=h2, port=3, latency=5, expire_time=115)
actual = self.router.table.get(h2)
self.assertEqual(
actual, expected,
"forwarding table entry for HOST h2 should be {}, got {}".format(
expected, actual
)
)
class TestSplitHorizon(TestDVRouterBase):
"""
Tests for split horizon behavior.
See docstring for the _add_test_routes_proper() method for initial link,
peer table, and forwarding table configurations. The current time starts
off at 100.
"""
def setUp(self):
self._set_up(poison_reverse=False, poison_expired=False,
poison_on_link_down=False, split_horizon=True, send_on_link_up=False)
self._add_test_routes_proper()
def test_single_neighbor_update(self):
"""Ensure neighbor isn't advertised its route for a destination."""
# Routes advertised out of each port.
all_ports = {1, 2, 3, 10}
with self._patch_send_routes(all_ports) as advertised_routes:
self.router.send_routes(force=True, single_port=None)
# Not every port gets every advertisement due to split horizon.
self._assert_route_ads_sent(
advertised_routes, {
1: {Route(self.h2, 5)},
2: {Route(self.h1, 8), Route(self.h2, 5)},
3: {Route(self.h1, 8)},
10: {Route(self.h1, 8), Route(self.h2, 5)}
}
)
class TestPoisonReverse(TestDVRouterBase):
"""
Tests for poison reverse.
See docstring for the _add_test_routes_proper() method for initial link,
peer table, and forwarding table configurations. The current time starts
off at 100.
"""
def setUp(self):
self._set_up(poison_reverse=True, poison_expired=False,
poison_on_link_down=True, split_horizon=False, send_on_link_up=False)
self._add_test_routes_proper()
def test_poison_reverse(self):
"""Ensures that poison reverse advertisements are sent."""
# Routes advertised out of each port.
with self._patch_send_routes(all_ports={1, 2, 3, 10}, allow_dup=True) as ads:
self.router.send_routes(force=True)
self._assert_route_ads_sent(
ads, {
1: {Route(self.h1, INFINITY), Route(self.h2, 5)},
2: {Route(self.h1, 8), Route(self.h2, 5)},
3: {Route(self.h1, 8), Route(self.h2, INFINITY)},
10: {Route(self.h1, 8), Route(self.h2, 5)},
}
)
class TestInfiniteLoops(TestDVRouterBase):
"""
Tests for poison reverse.
See docstring for the _add_test_routes_proper() method for initial link,
peer table, and forwarding table configurations. The current time starts
off at 100.