43e93ae192f3ad46e4c4dd64128d887b9fa4ad20
[mudpy.git] / mudpy / tests / selftest.py
1 # Copyright (c) 2004-2019 mudpy authors. Permission to use, copy,
2 # modify, and distribute this software is granted under terms
3 # provided in the LICENSE file distributed with this software.
4
5 import os
6 import pathlib
7 import re
8 import shutil
9 import subprocess
10 import sys
11 import telnetlib
12 import time
13
14 pidfile = "var/mudpy.pid"
15
16 test_account0_setup = (
17     (0, "Identify yourself:", "luser0"),
18     (0, "Enter your choice:", "n"),
19     (0, 'Enter a new password for "luser0":', "Test123"),
20     (0, "Enter the same new password again:", "Test123"),
21     (0, r"What would you like to do\?", "c"),
22     (0, "Pick a birth gender for your new avatar:", "f"),
23     (0, "Choose a name for her:", "1"),
24     (0, "What would you like to do?", "a"),
25     (0, "Whom would you like to awaken?", ""),
26 )
27
28 test_account1_setup = (
29     (1, "Identify yourself:", "luser1"),
30     (1, "Enter your choice:", "n"),
31     (1, 'Enter a new password for "luser1":', "Test456"),
32     (1, "Enter the same new password again:", "Test456"),
33     (1, r"What would you like to do\?", "c"),
34     (1, "Pick a birth gender for your new avatar:", "m"),
35     (1, "Choose a name for him:", "1"),
36     (1, "What would you like to do?", "a"),
37     (1, "Whom would you like to awaken?", ""),
38 )
39
40 test_actor_appears = (
41     (0, r"You suddenly realize that .* is here\.", ""),
42 )
43
44 test_explicit_punctuation = (
45     (0, "> ", "say Hello there!"),
46     (0, r'You exclaim, "Hello there\!"', ""),
47     (1, r'exclaims, "Hello there\!"', "say And you are?"),
48     (1, r'You ask, "And you are\?"', ""),
49     (0, r'asks, "And you are\?"', "say I'm me, of course."),
50     (0, r'''You say, "I'm me, of course\."''', ""),
51     (1, r'''says, "I'm me, of course\."''', "say I wouldn't be so sure..."),
52     (1, r'''You muse, "I wouldn't be so sure\.\.\."''', ""),
53     (0, r'''muses, "I wouldn't be so sure\.\.\."''', "say You mean,"),
54     (0, 'You begin, "You mean,"', ""),
55     (1, 'begins, "You mean,"', "say I know-"),
56     (1, 'You begin, "I know-"', ""),
57     (0, 'begins, "I know-"', "say Don't interrupt:"),
58     (0, r'''You begin, "Don't interrupt:"''', ""),
59     (1, r'''begins, "Don't interrupt:"''', "say I wasn't interrupting;"),
60     (1, r'''You begin, "I wasn't interrupting;"''', ""),
61     (0, r'''begins, "I wasn't interrupting;"''', ""),
62 )
63
64 test_implicit_punctuation = (
65     (0, '> ', "say Whatever"),
66     (0, r'You say, "Whatever\."', ""),
67     (1, r'says, "Whatever\."', ""),
68 )
69
70 test_typo_replacement = (
71     (1, '> ', "say That's what i think."),
72     (1, r'''You say, "That's what I think\."''', ""),
73     (0, r'''says, "That's what I think\."''', "say You know what i'd like."),
74     (0, r'''You say, "You know what I'd like\."''', ""),
75     (1, r'''says, "You know what I'd like\."''', "say Then i'll tell you."),
76     (1, r'''You say, "Then I'll tell you\."''', ""),
77     (0, r'''says, "Then I'll tell you\."''', "say Now i'm ready."),
78     (0, r'''You say, "Now I'm ready\."''', ""),
79     (1, r'''says, "Now I'm ready\."''', "say That's teh idea."),
80     (1, r'''You say, "That's the idea\."''', ""),
81     (0, r'''says, "That's the idea\."''', "say It's what theyre saying."),
82     (0, r'''You say, "It's what they're saying\."''', ""),
83     (1, r'''says, "It's what they're saying\."''', "say Well, youre right."),
84     (1, r'''You say, "Well, you're right\."''', ""),
85     (0, r'''says, "Well, you're right\."''', ""),
86 )
87
88 test_sentence_capitalization = (
89     (0, "> ", "say this sentence should start with a capital T."),
90     (0, 'You say, "This sentence', ""),
91     (1, 'says, "This sentence', ""),
92 )
93
94 test_chat_mode = (
95     (1, '> ', "chat"),
96     (1, r'(?s)Entering chat mode .*> \(chat\) ', "Feeling chatty."),
97     (1, r'You say, "Feeling chatty\."', "!chat"),
98     (0, r'says, "Feeling chatty\."', ""),
99     (1, '> ', "say Now less chatty."),
100     (1, r'You say, "Now less chatty\."', ""),
101     (0, r'says, "Now less chatty\."', ""),
102 )
103
104 test_wrapping = (
105     (0, '> ', "say " + 100 * "o"),
106     (1, r'says,\r\n"O[o]+\."', ""),
107 )
108
109 test_forbid_ansi_input = (
110     (0, '> ', "say \x1b[35mfoo\x1b[0m"),
111     (1, r'says, "\[35mfoo\[0m\."', ""),
112 )
113
114 test_movement = (
115     (0, "> ", "move north"),
116     (0, r"You exit to the north\.", ""),
117     (1, r"exits to the north\.", "move north"),
118     (0, r"arrives from the south\.", "move south"),
119     (0, r"You exit to the south\.", ""),
120     (1, r"exits to the south\.", "move south"),
121     (0, r"arrives from the north\.", "move east"),
122     (0, r"You exit to the east\.", ""),
123     (1, r"exits to the east\.", "move east"),
124     (0, r"arrives from the west\.", "move west"),
125     (0, r"You exit to the west\.", ""),
126     (1, r"exits to the west\.", "move west"),
127     (0, r"arrives from the east\.", "move up"),
128     (0, r"You exit upward\.", ""),
129     (1, r"exits upward\.", "move up"),
130     (0, r"arrives from below\.", "move down"),
131     (0, r"You exit downward\.", ""),
132     (1, r"exits downward\.", "move down"),
133     (0, r"arrives from above\.", ""),
134 )
135
136 test_actor_disappears = (
137     (1, "> ", "quit"),
138     (0, r"You suddenly wonder where .* went\.", ""),
139 )
140
141 test_account1_teardown = (
142     (1, "What would you like to do?", "d"),
143     (1, "Whom would you like to delete?", ""),
144     (1, "What would you like to do?", "p"),
145     (1, "permanently delete your account?", "y"),
146     (1, "Disconnecting...", ""),
147 )
148
149 test_admin_setup = (
150     (2, "Identify yourself:", "admin"),
151     (2, "Enter your choice:", "n"),
152     (2, 'Enter a new password for "admin":', "Test789"),
153     (2, "Enter the same new password again:", "Test789"),
154     (2, r"What would you like to do\?", "c"),
155     (2, "Pick a birth gender for your new avatar:", "m"),
156     (2, "Choose a name for him:", "1"),
157     (2, "What would you like to do?", "a"),
158     (2, "Whom would you like to awaken?", ""),
159 )
160
161 test_preferences = (
162     (0, "> ", "preferences"),
163     (0, r"prompt \x1b\[32m.*> ", "preferences prompt #"),
164     (0, r"# ", "preferences prompt"),
165     (0, r"#.*# ", "preferences prompt >"),
166     (2, "> ", "preferences loglevel 0"),
167     (2, "> ", "preferences"),
168     (2, r"loglevel \x1b\[32m0\x1b\[0m.*> ", "preferences loglevel zero"),
169     (2, r'''cannot be set to type "<class 'str'>"\..*> ''', ""),
170 )
171
172 test_crlf_eol = (
173     # Send a CR+LF at the end of the line instead of the default CR+NUL,
174     # to make sure they're treated the same
175     (2, "> ", b"say I use CR+LF as my EOL, not CR+NUL.\r\n"),
176     (2, r'You say, "I use CR\+LF as my EOL, not CR\+NUL\.".*> ', ""),
177 )
178
179 test_telnet_iac = (
180     # Send a double (escaped) IAC byte within other text, which should get
181     # unescaped and deduplicated to a single \xff in the buffer and then
182     # the line of input discarded as a non-ASCII sequence
183     (2, "> ", b"say argle\xff\xffbargle\r\0"),
184     (2, r"Non-ASCII characters from admin: b'say argle\\xffbargle'.*> ", ""),
185 )
186
187 test_telnet_unknown = (
188     # Send an unsupported negotiation command #127 which should get filtered
189     # from the line of input
190     (2, "> ", b"say glop\xff\x7fglyf\r\0"),
191     (2, r'Ignored unknown command 127 from admin\..*"Glopglyf\.".*> ', ""),
192 )
193
194 test_admin_restriction = (
195     (0, "> ", "help halt"),
196     (0, r"That is not an available command\.", "halt"),
197     (0, '(not sure what "halt" means|Arglebargle, glop-glyf)', ""),
198 )
199
200 test_admin_help = (
201     (2, "> ", "help"),
202     (2, r"halt.*Shut down the world\.", "help halt"),
203     (2, "This will save all active accounts", ""),
204 )
205
206 test_reload = (
207     (2, "> ", "reload"),
208     (2, r"Reloading all code modules, configs and data\."
209         r".* User admin reloaded the world\.",
210      "show element account.admin"),
211     (2, 'These are the properties of the "account.admin" element.*'
212         r'  \x1b\[32mpasshash:\r\n\x1b\[31m\$.*> ', ""),
213 )
214
215 test_set_facet = (
216     (2, "> ", "set actor.avatar_admin_0 gender female"),
217     (2, r'You have successfully \(re\)set the "gender" facet of element', ""),
218 )
219
220 test_set_refused = (
221     (2, "> ", "set mudpy.limit password_tries 10"),
222     (2, r'The "mudpy\.limit" element is kept in read-only file', ""),
223 )
224
225 test_show_version = (
226     (2, "> ", "show version"),
227     (2, r"Running mudpy .* on .* Python 3.*with.*pyyaml.*> ", ""),
228 )
229
230 test_show_files = (
231     (2, "> ", "show files"),
232     (2, r'These are the current files containing the universe:.*'
233         r'  \x1b\[31m\(rw\) \x1b\[32m/.*/account.yaml\x1b\[0m'
234         r' \x1b\[33m\[private\]\x1b\[0m.*> ', ""),
235 )
236
237 test_show_file = (
238     (2, "> ", "show file %s" %
239         os.path.join(os.getcwd(), "data/internal.yaml")),
240     (2, r'These are the nodes in the.*file:.*internal\.counters.*> ', ""),
241 )
242
243 test_show_groups = (
244     (2, "> ", "show groups"),
245     (2, r'These are the element groups:.*'
246         r'  \x1b\[32maccount\x1b\[0m.*> ', ""),
247 )
248
249 test_show_group = (
250     (2, "> ", "show group account"),
251     (2, r'These are the elements in the "account" group:.*'
252         r'  \x1b\[32maccount\.admin\x1b\[0m.*> ', ""),
253 )
254
255 test_show_element = (
256     (2, "> ", "show element mudpy.limit"),
257     (2, r'These are the properties of the "mudpy\.limit" element.*'
258         r'  \x1b\[32mpassword_tries: \x1b\[31m3.*> ',
259      "show element actor.avatar_admin_0"),
260     (2, r'These are the properties of the "actor.avatar_admin_0" element.*'
261         r'  \x1b\[32mgender: \x1b\[31mfemale.*> ', ""),
262 )
263
264 test_show_log = (
265     (2, "> ", "show log"),
266     (2, r"There are [0-9]+ log lines in memory and [0-9]+ at or above level "
267         r"[0-9]+\. The matching lines\r\nfrom [0-9]+ to [0-9]+ are:", ""),
268 )
269
270 test_custom_loglevel = (
271     (2, "> ", "set account.admin loglevel 2"),
272     (2, "You have successfully .*> ", "show log"),
273     (2, r"There are [0-9]+ log lines in memory and [0-9]+ at or above level "
274         r"[0-9]+\. The matching lines\r\nfrom [0-9]+ to [0-9]+ are:", ""),
275 )
276
277 test_invalid_loglevel = (
278     (2, "> ", "set account.admin loglevel two"),
279     (2, r'''Value "two" of type "<class 'str'>" cannot be coerced .*> ''', ""),
280 )
281
282 test_log_no_errors = (
283     (2, "> ", "show log 7"),
284     (2, r"None of the [0-9]+ lines in memory matches your request\.", ""),
285 )
286
287 final_cleanup = (
288     (0, "> ", "quit"),
289     (0, "What would you like to do?", "d"),
290     (0, "Whom would you like to delete?", ""),
291     (0, "What would you like to do?", "p"),
292     (0, "permanently delete your account?", "y"),
293     (0, "Disconnecting...", ""),
294     (2, "> ", "quit"),
295     (2, "What would you like to do?", "d"),
296     (2, "Whom would you like to delete?", ""),
297     (2, "What would you like to do?", "p"),
298     (2, "permanently delete your account?", "y"),
299     (2, "Disconnecting...", ""),
300 )
301
302 dialogue = (
303     (test_account0_setup, "first account setup"),
304     (test_account1_setup, "second account setup"),
305     (test_actor_appears, "actor spontaneous appearance"),
306     (test_explicit_punctuation, "explicit punctuation"),
307     (test_implicit_punctuation, "implicit punctuation"),
308     (test_typo_replacement, "typo replacement"),
309     (test_sentence_capitalization, "sentence capitalization"),
310     (test_chat_mode, "chat mode"),
311     (test_wrapping, "wrapping"),
312     (test_forbid_ansi_input, "raw escape input is filtered"),
313     (test_movement, "movement"),
314     (test_actor_disappears, "actor spontaneous disappearance"),
315     (test_account1_teardown, "second account teardown"),
316     (test_admin_setup, "admin account setup"),
317     (test_preferences, "set and show preferences"),
318     (test_crlf_eol, "send crlf from the client as eol"),
319     (test_telnet_iac, "escape stray telnet iac bytes"),
320     (test_telnet_unknown, "strip unknown telnet command"),
321     (test_admin_restriction, "restricted admin commands"),
322     (test_admin_help, "admin help"),
323     (test_reload, "reload"),
324     (test_set_facet, "set facet"),
325     (test_set_refused, "refuse altering read-only element"),
326     (test_show_version, "show version and diagnostic info"),
327     (test_show_files, "show a list of loaded files"),
328     (test_show_file, "show nodes from a specific file"),
329     (test_show_groups, "show groups"),
330     (test_show_group, "show group"),
331     (test_show_element, "show element"),
332     (test_show_log, "show log"),
333     (test_custom_loglevel, "custom loglevel"),
334     (test_invalid_loglevel, "invalid loglevel"),
335     (test_log_no_errors, "no errors logged"),
336     (final_cleanup, "delete remaining accounts"),
337 )
338
339
340 def start_service(config):
341     # Clean up any previously run daemon which didn't terminate
342     if os.path.exists(pidfile):
343         pidfd = open(pidfile)
344         pid = int(pidfd.read())
345         try:
346             # Stop the running service
347             os.kill(pid, 15)
348             time.sleep(1)
349         except ProcessLookupError:
350             # If there was no process, just remove the stale PID file
351             os.remove(pidfile)
352         # If there's a preexisting hung service, we can't proceed
353         assert not os.path.exists(pidfile)
354
355     # Clean up any previous test output
356     for f in pathlib.Path(".").glob("capture_*.log"):
357         # have to use .name here since remove() doesn't support passing a
358         # PosixPath argument until Python3.6
359         os.remove(f.name)
360     for d in ("data", "var"):
361         shutil.rmtree(d, ignore_errors=True)
362
363     # Start the service and wait for it to be ready for connections
364     service = subprocess.Popen(("mudpy", config),
365                                stdout=subprocess.PIPE,
366                                stderr=subprocess.PIPE)
367     time.sleep(1)
368     return(service)
369
370
371 def stop_service(service):
372     success = True
373
374     # The no-op case when no service was started
375     if service is None:
376         return(success)
377
378     # This handles when the service is running as a direct child process
379     service.terminate()
380     returncode = service.wait(10)
381     if returncode != 0:
382         tlog("\nERROR: Service exited with code %s." % returncode)
383         success = False
384
385     # This cleans up a daemonized and disassociated service
386     if os.path.exists(pidfile):
387         pidfd = open(pidfile)
388         pid = int(pidfd.read())
389         try:
390             # Stop the running service
391             os.kill(pid, 15)
392             time.sleep(1)
393         except ProcessLookupError:
394             # If there was no process, just remove the stale PID file
395             os.remove(pidfile)
396         # The PID file didn't disappear, so we have a hung service
397         if os.path.exists(pidfile):
398             tlog("\nERROR: Hung daemon with PID %s." % pid)
399             success = False
400
401     # Log the contents of stdout and stderr, if any
402     stdout, stderr = service.communicate()
403     tlog("\nRecording stdout as capture_stdout.log.")
404     serviceout = open("capture_stdout.log", "w")
405     serviceout.write(stdout.decode("utf-8"))
406     tlog("\nRecording stderr as capture_stderr.log.")
407     serviceerr = open("capture_stderr.log", "w")
408     serviceerr.write(stderr.decode("utf-8"))
409
410     return(success)
411
412
413 def tlog(message, quiet=False):
414     logfile = "capture_tests.log"
415     with open(logfile, "a") as logfd:
416         logfd.write(message + "\n")
417     if not quiet:
418         sys.stdout.write(message)
419     return True
420
421
422 def main():
423     captures = ["", "", ""]
424     lusers = [telnetlib.Telnet(), telnetlib.Telnet(), telnetlib.Telnet()]
425     success = True
426     start = time.time()
427     service = None
428     if len(sys.argv) > 1:
429         # Start the service if a config file was provided on the command line
430         service = start_service(sys.argv[1])
431     for luser in lusers:
432         luser.open("::1", 4000)
433     for test, description in dialogue:
434         tlog("\nTesting %s..." % description)
435         test_start = time.time()
436         for conversant, question, answer in test:
437             tlog("luser%s waiting for: %s" % (conversant, question),
438                  quiet=True)
439             try:
440                 index, match, received = lusers[conversant].expect(
441                     [re.compile(question.encode("utf-8"), flags=re.DOTALL)], 5)
442                 captures[conversant] += received.decode("utf-8")
443             except ConnectionResetError:
444                 tlog("\nERROR: Unable to connect to server.")
445                 success = False
446                 break
447             except EOFError:
448                 tlog("\nERROR: luser%s premature disconnection expecting:\n\n"
449                      "%s\n\n"
450                      "Check the end of capture_%s.log for received data."
451                      % (conversant, question, conversant))
452                 success = False
453                 break
454             try:
455                 captures[conversant] += lusers[
456                     conversant].read_very_eager().decode("utf-8")
457             except Exception:
458                 pass
459             if index is not 0:
460                 tlog("\nERROR: luser%s did not receive expected string:\n\n"
461                      "%s\n\n"
462                      "Check the end of capture_%s.log for received data."
463                      % (conversant, question, conversant))
464                 success = False
465                 break
466             if type(answer) is str:
467                 tlog("luser%s sending: %s" % (conversant, answer), quiet=True)
468                 lusers[conversant].write(("%s\r\0" % answer).encode("utf-8"))
469                 captures[conversant] += "%s\r\n" % answer
470             elif type(answer) is bytes:
471                 tlog("luser%s sending raw bytes: %s" % (conversant, answer),
472                      quiet=True)
473                 lusers[conversant].get_socket().send(answer)
474                 captures[conversant] += "!!!RAW BYTES: %s" % answer
475             else:
476                 tlog("\nERROR: answer provided with unsupported type %s"
477                      % type(answer))
478                 success = False
479                 break
480         if not success:
481             break
482         tlog("Completed in %.3f seconds." % (time.time() - test_start))
483     duration = time.time() - start
484     for conversant in range(len(captures)):
485         try:
486             captures[conversant] += lusers[
487                 conversant].read_very_eager().decode("utf-8")
488         except Exception:
489             pass
490         lusers[conversant].close()
491         logfile = "capture_%s.log" % conversant
492         tlog("\nRecording session %s as %s." % (conversant, logfile))
493         log = open(logfile, "w")
494         log.write(captures[conversant])
495         log.close()
496     if not stop_service(service):
497         success = False
498     tlog("\nRan %s tests in %.3f seconds." % (len(dialogue), duration))
499     if success:
500         tlog("\nSUCCESS\n")
501     else:
502         tlog("\nFAILURE\n")
503         sys.exit(1)
504
505
506 if __name__ == '__main__':
507     sys.exit(main())