A Discrete-Event Network Simulator
API
python-unit-tests.py
Go to the documentation of this file.
1#! /usr/bin/env python3
2
3# Copyright (C) 2008-2011 INESC Porto
4
5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation; either version 2 of the License, or
8# (at your option) any later version.
9
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14
15# You should have received a copy of the GNU General Public License
16# along with this program; if not, write to the Free Software
17# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
19# Author: Gustavo J. A. M. Carneiro <gjc@inescporto.pt>
20
21import unittest
22from ns import ns
23import sys
24
25UINT32_MAX = 0xFFFFFFFF
26
27
28
29class TestSimulator(unittest.TestCase):
30
38
39 def testScheduleNow(self):
40 """! Test schedule now
41 @param self this object
42 @return none
43 """
44 def callback(args: ns.cppyy.gbl.std.vector) -> None:
45 """! Callback function
46 @param args arguments
47 return none
48 """
49 import copy
50 self._args_received = list(map(lambda x: x.decode("utf-8"), args))
51 self._cb_time = ns.Simulator.Now()
52 ns.Simulator.Destroy()
53 self._args_received = None
54 self._cb_time = None
55 ns.cppyy.cppdef("""
56 EventImpl* pythonMakeEvent(void (*f)(std::vector<std::string>), std::vector<std::string> l)
57 {
58 return MakeEvent(f, l);
59 }
60 """)
61 event = ns.cppyy.gbl.pythonMakeEvent(callback, sys.argv)
62 ns.Simulator.ScheduleNow(event)
63 ns.Simulator.Run()
64 self.assertListEqual(self._args_received, sys.argv)
65 self.assertEqual(self._cb_time.GetSeconds(), 0.0)
66
67 def testSchedule(self):
68 """! Test schedule
69 @param self this object
70 @return none
71 """
72 def callback(args: ns.cppyy.gbl.std.vector):
73 """! Callback function
74 @param args arguments
75 @return none
76 """
77 self._args_received = list(map(lambda x: x.decode("utf-8"), args))
78 self._cb_time = ns.Simulator.Now()
79 ns.Simulator.Destroy()
80 self._args_received = None
81 self._cb_time = None
82 ns.cppyy.cppdef("""
83 EventImpl* pythonMakeEvent2(void (*f)(std::vector<std::string>), std::vector<std::string> l)
84 {
85 return MakeEvent(f, l);
86 }
87 """)
88 event = ns.cppyy.gbl.pythonMakeEvent2(callback, sys.argv)
89 ns.Simulator.Schedule(ns.Seconds(123), event)
90 ns.Simulator.Run()
91 self.assertListEqual(self._args_received, sys.argv)
92 self.assertEqual(self._cb_time.GetSeconds(), 123.0)
93
95 """! Test schedule destroy
96 @param self this object
97 @return none
98 """
99 def callback(args: ns.cppyy.gbl.std.vector):
100 """! Callback function
101 @param args
102 @return none
103 """
104 self._args_received = list(map(lambda x: x.decode("utf-8"), args))
105 self._cb_time = ns.Simulator.Now()
106 ns.Simulator.Destroy()
107 self._args_received = None
108 self._cb_time = None
109 ns.cppyy.cppdef("void null(){ return; }")
110 ns.Simulator.Schedule(ns.Seconds(123), ns.cppyy.gbl.null)
111 ns.cppyy.cppdef("""
112 EventImpl* pythonMakeEvent3(void (*f)(std::vector<std::string>), std::vector<std::string> l)
113 {
114 return MakeEvent(f, l);
115 }
116 """)
117 event = ns.cppyy.gbl.pythonMakeEvent3(callback, sys.argv)
118 ns.Simulator.ScheduleDestroy(event)
119 ns.Simulator.Run()
120 ns.Simulator.Destroy()
121 self.assertListEqual(self._args_received, sys.argv)
122 self.assertEqual(self._cb_time.GetSeconds(), 123.0)
123
125 """! Test schedule with context
126 @param self this object
127 @return none
128 """
129 def callback(context, args: ns.cppyy.gbl.std.vector):
130 """! Callback
131 @param context the cntet
132 @param args the arguments
133 @return none
134 """
135 self._context_received = context
136 self._args_received = list(map(lambda x: x.decode("utf-8"), args))
137 self._cb_time = ns.Simulator.Now()
138 ns.Simulator.Destroy()
139 self._args_received = None
140 self._cb_time = None
141 self._context_received = None
142 ns.cppyy.cppdef("""
143 EventImpl* pythonMakeEvent4(void (*f)(uint32_t, std::vector<std::string>), uint32_t context, std::vector<std::string> l)
144 {
145 return MakeEvent(f, context, l);
146 }
147 """)
148 event = ns.cppyy.gbl.pythonMakeEvent4(callback, 54321, sys.argv)
149 ns.Simulator.ScheduleWithContext(54321, ns.Seconds(123), event)
150 ns.Simulator.Run()
151 self.assertEqual(self._context_received, 54321)
152 self.assertListEqual(self._args_received, sys.argv)
153 self.assertEqual(self._cb_time.GetSeconds(), 123.0)
154
156 """! Test time comparison
157 @param self this object
158 @return none
159 """
160 self.assertTrue(ns.Seconds(123) == ns.Seconds(123))
161 self.assertTrue(ns.Seconds(123) >= ns.Seconds(123))
162 self.assertTrue(ns.Seconds(123) <= ns.Seconds(123))
163 self.assertTrue(ns.Seconds(124) > ns.Seconds(123))
164 self.assertTrue(ns.Seconds(123) < ns.Seconds(124))
165
167 """! Test numeric operations
168 @param self this object
169 @return none
170 """
171 self.assertEqual(ns.Seconds(10) + ns.Seconds(5), ns.Seconds(15))
172 self.assertEqual(ns.Seconds(10) - ns.Seconds(5), ns.Seconds(5))
173
174 v1 = ns.int64x64_t(5.0)*ns.int64x64_t(10)
175 self.assertEqual(v1, ns.int64x64_t(50))
176
177 def testConfig(self):
178 """! Test configuration
179 @param self this object
180 @return none
181 """
182 ns.Config.SetDefault("ns3::OnOffApplication::PacketSize", ns.core.UintegerValue(123))
183 # hm.. no Config.Get?
184
185 def testSocket(self):
186 """! Test socket
187 @param self
188 @return none
189 """
190 nc = ns.NodeContainer(1)
191 node = nc.Get(0)
192 internet = ns.CreateObject("InternetStackHelper")
193 internet.Install(node)
195
196 def python_rx_callback(socket) -> None:
197 self._received_packet = socket.Recv(maxSize=UINT32_MAX, flags=0)
198
199 ns.cppyy.cppdef("""
200 Callback<void,ns3::Ptr<ns3::Socket> > make_rx_callback(void(*func)(Ptr<Socket>))
201 {
202 return MakeCallback(func);
203 }
204 """)
205
206 sink = ns.network.Socket.CreateSocket(node, ns.core.TypeId.LookupByName("ns3::UdpSocketFactory"))
207 sink.Bind(ns.addressFromInetSocketAddress(ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), 80)))
208 sink.SetRecvCallback(ns.cppyy.gbl.make_rx_callback(python_rx_callback))
209
210 source = ns.network.Socket.CreateSocket(node, ns.core.TypeId.LookupByName("ns3::UdpSocketFactory"))
211 source.SendTo(ns.network.Packet(19), 0, ns.addressFromInetSocketAddress(ns.network.InetSocketAddress(ns.network.Ipv4Address("127.0.0.1"), 80)))
212
213 ns.Simulator.Run()
214 self.assertTrue(self._received_packet is not None)
215 self.assertEqual(self._received_packet.GetSize(), 19)
216
217 # Delete Ptr<>'s on the python side to let C++ clean them
218 del internet
219
220 def testAttributes(self):
221 """! Test attributes function
222 @param self this object
223 @return none
224 """
225 # Templated class DropTailQueue<Packet> in C++
226 queue = ns.CreateObject("DropTailQueue<Packet>")
227 queueSizeValue = ns.network.QueueSizeValue (ns.network.QueueSize ("500p"))
228 queue.SetAttribute("MaxSize", queueSizeValue)
229
230 limit = ns.network.QueueSizeValue()
231 queue.GetAttribute("MaxSize", limit)
232 self.assertEqual(limit.Get(), ns.network.QueueSize ("500p"))
233
234
235 mobility = ns.CreateObject("RandomWaypointMobilityModel")
236 ptr = ns.CreateObject("PointerValue")
237 mobility.GetAttribute("PositionAllocator", ptr)
238 self.assertEqual(ptr.GetObject(), ns.core.Ptr["Object"](ns.cppyy.nullptr))
239
240 pos = ns.mobility.ListPositionAllocator()
241 ptr.SetObject(pos)
242 mobility.SetAttribute("PositionAllocator", ptr)
243
244 ptr2 = ns.CreateObject("PointerValue")
245 mobility.GetAttribute("PositionAllocator", ptr2)
246 self.assertNotEqual(ptr.GetObject(), ns.core.Ptr["Object"](ns.cppyy.nullptr))
247
248 # Delete Ptr<>'s on the python side to let C++ clean them
249 del queue, mobility, ptr, ptr2
250
251 def testIdentity(self):
252 """! Test identify
253 @param self this object
254 @return none
255 """
256 csma = ns.CreateObject("CsmaNetDevice")
257 channel = ns.CreateObject("CsmaChannel")
258 csma.Attach(channel)
259
260 c1 = csma.GetChannel()
261 c2 = csma.GetChannel()
262
263 self.assertEqual(c1, c2)
264
265 # Delete Ptr<>'s on the python side to let C++ clean them
266 del csma, channel
267
268 def testTypeId(self):
269 """! Test type ID
270 @param self this object
271 @return none
272 """
273 ok, typeId1 = ns.LookupByNameFailSafe("ns3::UdpSocketFactory")
274 self.assertTrue(ok)
275 self.assertEqual(typeId1.GetName (), "ns3::UdpSocketFactory")
276
277 ok, typeId1 = ns.LookupByNameFailSafe("ns3::__InvalidTypeName__")
278 self.assertFalse(ok)
279
281 """! Test command line
282 @param self this object
283 @return none
284 """
285 from ctypes import c_bool, c_int, c_double, c_char_p, create_string_buffer
286
287 test1 = c_bool(True)
288 test2 = c_int(42)
289 test3 = c_double(3.1415)
290 BUFFLEN = 40
291 test4Buffer = create_string_buffer(b"this is a test option", BUFFLEN)
292 test4 = c_char_p(test4Buffer.raw)
293
294 cmd = ns.core.CommandLine(__file__)
295 cmd.AddValue("Test1", "this is a test option", test1)
296 cmd.AddValue("Test2", "this is a test option", test2)
297 cmd.AddValue("Test3", "this is a test option", test3)
298 cmd.AddValue("Test4", "this is a test option", test4, BUFFLEN)
299
300 cmd.Parse(["python"])
301 self.assertEqual(test1.value, True)
302 self.assertEqual(test2.value, 42)
303 self.assertEqual(test3.value, 3.1415)
304 self.assertEqual(test4.value, b"this is a test option")
305
306 cmd.Parse(["python", "--Test1=false", "--Test2=0", "--Test3=0.0"])
307 self.assertEqual(test1.value, False)
308 self.assertEqual(test2.value, 0)
309 self.assertEqual(test3.value, 0.0)
310
311 cmd.Parse(["python", "--Test4=new_string"])
312 self.assertEqual(test4.value, b"new_string")
313
314 def testSubclass(self):
315 """! Test subclass
316 @param self this object
317 @return none
318 """
319
320 class MyNode(ns.network.Node):
321 def GetLocalTime(self) -> ns.Time:
322 return ns.Seconds(10)
323
324 node = MyNode()
325 forced_local_time = node.GetLocalTime()
326 self.assertEqual(forced_local_time, ns.Seconds(10))
327 del node
328
329
330if __name__ == '__main__':
331 unittest.main(verbosity=1, failfast=True)
def testScheduleDestroy(self)
Test schedule destroy.
def testCommandLine(self)
Test command line.
def testTimeNumericOperations(self)
Test numeric operations.
def testScheduleNow(self)
Test schedule now.
def testTypeId(self)
Test type ID.
def testSubclass(self)
Test subclass.
def testSchedule(self)
Test schedule.
def testScheduleWithContext(self)
Test schedule with context.
def testAttributes(self)
Test attributes function.
def testSocket(self)
Test socket.
def testTimeComparison(self)
Test time comparison.
def testConfig(self)
Test configuration.
def testIdentity(self)
Test identify.
EventImpl * MakeEvent(void(*f)())
Make an EventImpl from a function pointer taking varying numbers of arguments.
Definition: make-event.cc:36
Callback< R, Args... > MakeCallback(R(T::*memPtr)(Args...), OBJ objPtr)
Build Callbacks for class method members which take varying numbers of arguments and potentially retu...
Definition: callback.h:691
uint32_t GetSize(Ptr< const Packet > packet, const WifiMacHeader *hdr, bool isAmpdu)
Return the total size of the packet after WifiMacHeader and FCS trailer have been added.
Definition: wifi-utils.cc:132
#define list