first batch of license fixes (boring)
[oweals/gnunet.git] / src / integration-tests / gnunet_pyexpect.py.in
1 #!@PYTHON@
2 #    This file is part of GNUnet.
3 #    (C) 2010 Christian Grothoff (and other contributing authors)
4 #
5 #    GNUnet is free software: you can redistribute it and/or modify it
6 #    under the terms of the GNU General Public License as published
7 #    by the Free Software Foundation, either version 3 of the License,
8 #    or (at your option) any later version.
9 #
10 #    GNUnet is distributed in the hope that it will be useful, but
11 #    WITHOUT ANY WARRANTY; without even the implied warranty of
12 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #    Affero General Public License for more details.
14 #
15 # Testcase for gnunet-peerinfo
16 from __future__ import print_function
17 import os
18 import re
19 import subprocess
20 import sys
21 import shutil
22 import time
23
24 class pexpect (object):
25   def __init__ (self):
26     super (pexpect, self).__init__ ()
27
28   def spawn (self, stdin, arglist, *pargs, **kwargs):
29     env = kwargs.pop ('env', None)
30     if env is None:
31       env = os.environ.copy ()
32     # This messes up some testcases, disable log redirection
33     env.pop ('GNUNET_FORCE_LOGFILE', None)
34     self.proc = subprocess.Popen (arglist, *pargs, env=env, **kwargs)
35     if self.proc is None:
36       print ("Failed to spawn a process {0}".format (arglist))
37       sys.exit (1)
38     if stdin is not None:
39       self.stdo, self.stde = self.proc.communicate (stdin)
40     else:
41       self.stdo, self.stde = self.proc.communicate ()
42     return self.proc
43
44   def expect (self, s, r, flags=0):
45     stream = self.stdo if s == 'stdout' else self.stde
46     if isinstance (r, str):
47       if r == "EOF":
48         if len (stream) == 0:
49           return True
50         else:
51           print ("Failed to find `{1}' in {0}, which is `{2}' ({3})".format (s, r, stream, len (stream)))
52           sys.exit (2)
53       raise ValueError ("Argument `r' should be an instance of re.RegexObject or a special string, but is `{0}'".format (r))
54     m = r.search (stream, flags)
55     if not m:
56       print ("Failed to find `{1}' in {0}, which is is `{2}'".format (s, r.pattern, stream))
57       sys.exit (2)
58     stream = stream[m.end ():]
59     if s == 'stdout':
60       self.stdo = stream
61     else:
62       self.stde = stream
63     return m
64
65   def read (self, s, size=-1):
66     stream = self.stdo if s == 'stdout' else self.stde
67     result = ""
68     if size < 0:
69       result = stream
70       new_stream = ""
71     else:
72       result = stream[0:size]
73       new_stream = stream[size:]
74     if s == 'stdout':
75       self.stdo = new_stream
76     else:
77       self.stde = new_stream
78     return result