497d9701771b21f93a27085e7e2ae627a1e1e511
[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_escape_macros = (
115     (0, '> ', "say $(red)bar$(nrm)"),
116     (1, r'says, "\$\(red\)bar\$\(nrm\)."', ""),
117 )
118
119 test_movement = (
120     (0, "> ", "move north"),
121     (0, r"You exit to the north\.", ""),
122     (1, r"exits to the north\.", "move north"),
123     (0, r"arrives from the south\.", "move south"),
124     (0, r"You exit to the south\.", ""),
125     (1, r"exits to the south\.", "move south"),
126     (0, r"arrives from the north\.", "move east"),
127     (0, r"You exit to the east\.", ""),
128     (1, r"exits to the east\.", "move east"),
129     (0, r"arrives from the west\.", "move west"),
130     (0, r"You exit to the west\.", ""),
131     (1, r"exits to the west\.", "move west"),
132     (0, r"arrives from the east\.", "move up"),
133     (0, r"You exit upward\.", ""),
134     (1, r"exits upward\.", "move up"),
135     (0, r"arrives from below\.", "move down"),
136     (0, r"You exit downward\.", ""),
137     (1, r"exits downward\.", "move down"),
138     (0, r"arrives from above\.", ""),
139 )
140
141 test_actor_disappears = (
142     (1, "> ", "quit"),
143     (0, r"You suddenly wonder where .* went\.", ""),
144 )
145
146 test_account1_teardown = (
147     (1, "What would you like to do?", "d"),
148     (1, "Whom would you like to delete?", ""),
149     (1, "What would you like to do?", "p"),
150     (1, "permanently delete your account?", "y"),
151     (1, "Disconnecting...", ""),
152 )
153
154 test_admin_setup = (
155     (2, "Identify yourself:", "admin"),
156     (2, "Enter your choice:", "n"),
157     (2, 'Enter a new password for "admin":', "Test789"),
158     (2, "Enter the same new password again:", "Test789"),
159     (2, r"What would you like to do\?", "c"),
160     (2, "Pick a birth gender for your new avatar:", "m"),
161     (2, "Choose a name for him:", "1"),
162     (2, "What would you like to do?", "a"),
163     (2, "Whom would you like to awaken?", ""),
164 )
165
166 test_preferences = (
167     (0, "> ", "preferences"),
168     (0, r"prompt \x1b\[32m.*> ", "preferences prompt $(foo)"),
169     (0, r"\$\(foo\) ", "preferences prompt"),
170     (0, r"\$\(foo\).*\$\(foo\) ", "preferences prompt $(time)>"),
171     (0, "[0-9]> ", "preferences prompt >"),
172     (2, "> ", "preferences loglevel 0"),
173     (2, "> ", "preferences"),
174     (2, r"loglevel \x1b\[32m0\x1b\[0m.*> ", "preferences loglevel zero"),
175     (2, r'''cannot be set to type "<class 'str'>"\..*> ''', ""),
176 )
177
178 test_crlf_eol = (
179     # Send a CR+LF at the end of the line instead of the default CR+NUL,
180     # to make sure they're treated the same
181     (2, "> ", b"say I use CR+LF as my EOL, not CR+NUL.\r\n"),
182     (2, r'You say, "I use CR\+LF as my EOL, not CR\+NUL\.".*> ', ""),
183 )
184
185 test_telnet_iac = (
186     # Send a double (escaped) IAC byte within other text, which should get
187     # unescaped and deduplicated to a single \xff in the buffer and then
188     # the line of input discarded as a non-ASCII sequence
189     (2, "> ", b"say argle\xff\xffbargle\r\0"),
190     (2, r"Non-ASCII characters from admin: b'say.*argle\\xffbargle'.*> ", ""),
191 )
192
193 test_telnet_unknown_command = (
194     # Send an unsupported negotiation command #127 which should get filtered
195     # from the line of input
196     (2, "> ", b"say glop\xff\x7fglyf\r\0"),
197     (2, r'Ignored unknown command 127 from admin\..*"Glopglyf\.".*> ', ""),
198 )
199
200 test_telnet_unknown_option = (
201     # Send an unassigned negotiation option #127 which should get logged
202     (2, "> ", b"\xff\xfe\x7f\r\0"),
203     (2, r'''Received "don't 127" from admin\..*> ''', ""),
204 )
205
206 test_admin_restriction = (
207     (0, "> ", "help halt"),
208     (0, r"That is not an available command\.", "halt"),
209     (0, '(not sure what "halt" means|Arglebargle, glop-glyf)', ""),
210 )
211
212 test_admin_help = (
213     (2, "> ", "help"),
214     (2, r"halt.*Shut down the world\.", "help halt"),
215     (2, "This will save all active accounts", ""),
216 )
217
218 test_abbrev = (
219     (0, "> ", "help mov"),
220     (0, r"Move in a specific direction\.", "mov north"),
221     (0, r"You exit to the north\.", ""),
222 )
223
224 test_reload = (
225     (2, "> ", "reload"),
226     (2, r"Reloading all code modules, configs and data\."
227         r".* User admin reloaded the world\.",
228      "show element account.admin"),
229     (2, 'These are the properties of the "account.admin" element.*'
230         r'  \x1b\[32mpasshash:\r\n\x1b\[31m\$.*> ', ""),
231 )
232
233 test_set_facet = (
234     (2, "> ", "set actor.avatar_admin_0 gender female"),
235     (2, r'You have successfully \(re\)set the "gender" facet of element', ""),
236 )
237
238 test_set_refused = (
239     (2, "> ", "set mudpy.limit password_tries 10"),
240     (2, r'The "mudpy\.limit" element is kept in read-only file', ""),
241 )
242
243 test_show_version = (
244     (2, "> ", "show version"),
245     (2, r"Running mudpy .* on .* Python 3.*with.*pyyaml.*> ", ""),
246 )
247
248 test_show_time = (
249     (2, "> ", "show time"),
250     (2, r"\r\n[0-9]+ increments elapsed.*> ", ""),
251 )
252
253 test_show_files = (
254     (2, "> ", "show files"),
255     (2, r'These are the current files containing the universe:.*'
256         r'  \x1b\[31m\(rw\) \x1b\[32m/.*/account.yaml\x1b\[0m'
257         r' \x1b\[33m\[private\]\x1b\[0m.*> ', ""),
258 )
259
260 test_show_file = (
261     (2, "> ", "show file %s" %
262         os.path.join(os.getcwd(), "data/internal.yaml")),
263     (2, r'These are the nodes in the.*file:.*internal\.counters.*> ', ""),
264 )
265
266 test_show_groups = (
267     (2, "> ", "show groups"),
268     (2, r'These are the element groups:.*'
269         r'  \x1b\[32maccount\x1b\[0m.*> ', ""),
270 )
271
272 test_show_group = (
273     (2, "> ", "show group account"),
274     (2, r'These are the elements in the "account" group:.*'
275         r'  \x1b\[32maccount\.admin\x1b\[0m.*> ', ""),
276 )
277
278 test_show_element = (
279     (2, "> ", "show element mudpy.limit"),
280     (2, r'These are the properties of the "mudpy\.limit" element.*'
281         r'  \x1b\[32mpassword_tries: \x1b\[31m3.*> ',
282      "show element actor.avatar_admin_0"),
283     (2, r'These are the properties of the "actor.avatar_admin_0" element.*'
284         r'  \x1b\[32mgender: \x1b\[31mfemale.*> ', ""),
285 )
286
287 test_show_log = (
288     (2, "> ", "show log"),
289     (2, r"There are [0-9]+ log lines in memory and [0-9]+ at or above level "
290         r"[0-9]+\. The matching lines\r\nfrom [0-9]+ to [0-9]+ are:", ""),
291 )
292
293 test_custom_loglevel = (
294     (2, "> ", "set account.admin loglevel 2"),
295     (2, "You have successfully .*> ", "show log"),
296     (2, r"There are [0-9]+ log lines in memory and [0-9]+ at or above level "
297         r"[0-9]+\. The matching lines\r\nfrom [0-9]+ to [0-9]+ are:", ""),
298 )
299
300 test_invalid_loglevel = (
301     (2, "> ", "set account.admin loglevel two"),
302     (2, r'''Value "two" of type "<class 'str'>" cannot be coerced .*> ''', ""),
303 )
304
305 test_log_no_errors = (
306     (2, "> ", "show log 7"),
307     (2, r"None of the [0-9]+ lines in memory matches your request\.", ""),
308 )
309
310 final_cleanup = (
311     (0, "> ", "quit"),
312     (0, "What would you like to do?", "d"),
313     (0, "Whom would you like to delete?", ""),
314     (0, "What would you like to do?", "p"),
315     (0, "permanently delete your account?", "y"),
316     (0, "Disconnecting...", ""),
317     (2, "> ", "quit"),
318     (2, "What would you like to do?", "d"),
319     (2, "Whom would you like to delete?", ""),
320     (2, "What would you like to do?", "p"),
321     (2, "permanently delete your account?", "y"),
322     (2, "Disconnecting...", ""),
323 )
324
325 dialogue = (
326     (test_account0_setup, "first account setup"),
327     (test_account1_setup, "second account setup"),
328     (test_actor_appears, "actor spontaneous appearance"),
329     (test_explicit_punctuation, "explicit punctuation"),
330     (test_implicit_punctuation, "implicit punctuation"),
331     (test_typo_replacement, "typo replacement"),
332     (test_sentence_capitalization, "sentence capitalization"),
333     (test_chat_mode, "chat mode"),
334     (test_wrapping, "wrapping"),
335     (test_forbid_ansi_input, "raw escape input is filtered"),
336     (test_escape_macros, "replacement macros are escaped"),
337     (test_movement, "movement"),
338     (test_actor_disappears, "actor spontaneous disappearance"),
339     (test_account1_teardown, "second account teardown"),
340     (test_admin_setup, "admin account setup"),
341     (test_preferences, "set and show preferences"),
342     (test_crlf_eol, "send crlf from the client as eol"),
343     (test_telnet_iac, "escape stray telnet iac bytes"),
344     (test_telnet_unknown_command, "strip unknown telnet command"),
345     (test_telnet_unknown_option, "log unknown telnet option"),
346     (test_admin_restriction, "restricted admin commands"),
347     (test_admin_help, "admin help"),
348     (test_abbrev, "command abbreviation"),
349     (test_reload, "reload"),
350     (test_set_facet, "set facet"),
351     (test_set_refused, "refuse altering read-only element"),
352     (test_show_version, "show version and diagnostic info"),
353     (test_show_time, "show elapsed world clock increments"),
354     (test_show_files, "show a list of loaded files"),
355     (test_show_file, "show nodes from a specific file"),
356     (test_show_groups, "show groups"),
357     (test_show_group, "show group"),
358     (test_show_element, "show element"),
359     (test_show_log, "show log"),
360     (test_custom_loglevel, "custom loglevel"),
361     (test_invalid_loglevel, "invalid loglevel"),
362     (test_log_no_errors, "no errors logged"),
363     (final_cleanup, "delete remaining accounts"),
364 )
365
366
367 def start_service(config):
368     # Clean up any previously run daemon which didn't terminate
369     if os.path.exists(pidfile):
370         pidfd = open(pidfile)
371         pid = int(pidfd.read())
372         try:
373             # Stop the running service
374             os.kill(pid, 15)
375             time.sleep(1)
376         except ProcessLookupError:
377             # If there was no process, just remove the stale PID file
378             os.remove(pidfile)
379         # If there's a preexisting hung service, we can't proceed
380         assert not os.path.exists(pidfile)
381
382     # Clean up any previous test output
383     for f in pathlib.Path(".").glob("capture_*.log"):
384         # have to use .name here since remove() doesn't support passing a
385         # PosixPath argument until Python3.6
386         os.remove(f.name)
387     for d in ("data", "var"):
388         shutil.rmtree(d, ignore_errors=True)
389
390     # Start the service and wait for it to be ready for connections
391     service = subprocess.Popen(("mudpy", config),
392                                stdout=subprocess.PIPE,
393                                stderr=subprocess.PIPE)
394     time.sleep(1)
395     return(service)
396
397
398 def stop_service(service):
399     success = True
400
401     # The no-op case when no service was started
402     if service is None:
403         return(success)
404
405     # This handles when the service is running as a direct child process
406     service.terminate()
407     returncode = service.wait(10)
408     if returncode != 0:
409         tlog("\nERROR: Service exited with code %s." % returncode)
410         success = False
411
412     # This cleans up a daemonized and disassociated service
413     if os.path.exists(pidfile):
414         pidfd = open(pidfile)
415         pid = int(pidfd.read())
416         try:
417             # Stop the running service
418             os.kill(pid, 15)
419             time.sleep(1)
420         except ProcessLookupError:
421             # If there was no process, just remove the stale PID file
422             os.remove(pidfile)
423         # The PID file didn't disappear, so we have a hung service
424         if os.path.exists(pidfile):
425             tlog("\nERROR: Hung daemon with PID %s." % pid)
426             success = False
427
428     # Log the contents of stdout and stderr, if any
429     stdout, stderr = service.communicate()
430     tlog("\nRecording stdout as capture_stdout.log.")
431     serviceout = open("capture_stdout.log", "w")
432     serviceout.write(stdout.decode("utf-8"))
433     tlog("\nRecording stderr as capture_stderr.log.")
434     serviceerr = open("capture_stderr.log", "w")
435     serviceerr.write(stderr.decode("utf-8"))
436
437     return(success)
438
439
440 def tlog(message, quiet=False):
441     logfile = "capture_tests.log"
442     with open(logfile, "a") as logfd:
443         logfd.write(message + "\n")
444     if not quiet:
445         sys.stdout.write(message)
446     return True
447
448
449 def option_callback(telnet_socket, command, option):
450     if option == b'\x7f':
451         # We use this unassigned option value as a canary, so short-circuit
452         # any response to avoid endlessly looping
453         pass
454     elif command in (telnetlib.DO, telnetlib.DONT):
455         telnet_socket.send(telnetlib.IAC + telnetlib.WONT + option)
456     elif command in (telnetlib.WILL, telnetlib.WONT):
457         telnet_socket.send(telnetlib.IAC + telnetlib.DONT + option)
458
459
460 def main():
461     captures = ["", "", ""]
462     lusers = [telnetlib.Telnet(), telnetlib.Telnet(), telnetlib.Telnet()]
463     success = True
464     start = time.time()
465     service = None
466     if len(sys.argv) > 1:
467         # Start the service if a config file was provided on the command line
468         service = start_service(sys.argv[1])
469     for luser in lusers:
470         luser.open("::1", 4000)
471         luser.set_option_negotiation_callback(option_callback)
472     for test, description in dialogue:
473         tlog("\nTesting %s..." % description)
474         test_start = time.time()
475         for conversant, question, answer in test:
476             tlog("luser%s waiting for: %s" % (conversant, question),
477                  quiet=True)
478             try:
479                 index, match, received = lusers[conversant].expect(
480                     [re.compile(question.encode("utf-8"), flags=re.DOTALL)], 5)
481                 captures[conversant] += received.decode("utf-8")
482             except ConnectionResetError:
483                 tlog("\nERROR: Unable to connect to server.")
484                 success = False
485                 break
486             except EOFError:
487                 tlog("\nERROR: luser%s premature disconnection expecting:\n\n"
488                      "%s\n\n"
489                      "Check the end of capture_%s.log for received data."
490                      % (conversant, question, conversant))
491                 success = False
492                 break
493             try:
494                 captures[conversant] += lusers[
495                     conversant].read_very_eager().decode("utf-8")
496             except Exception:
497                 pass
498             if index != 0:
499                 tlog("\nERROR: luser%s did not receive expected string:\n\n"
500                      "%s\n\n"
501                      "Check the end of capture_%s.log for received data."
502                      % (conversant, question, conversant))
503                 success = False
504                 break
505             if type(answer) is str:
506                 tlog("luser%s sending: %s" % (conversant, answer), quiet=True)
507                 lusers[conversant].write(("%s\r\0" % answer).encode("utf-8"))
508                 captures[conversant] += "%s\r\n" % answer
509             elif type(answer) is bytes:
510                 tlog("luser%s sending raw bytes: %s" % (conversant, answer),
511                      quiet=True)
512                 lusers[conversant].get_socket().send(answer)
513                 captures[conversant] += "!!!RAW BYTES: %s" % answer
514             else:
515                 tlog("\nERROR: answer provided with unsupported type %s"
516                      % type(answer))
517                 success = False
518                 break
519         if not success:
520             break
521         tlog("Completed in %.3f seconds." % (time.time() - test_start))
522     duration = time.time() - start
523     for conversant in range(len(captures)):
524         try:
525             captures[conversant] += lusers[
526                 conversant].read_very_eager().decode("utf-8")
527         except Exception:
528             pass
529         lusers[conversant].close()
530         logfile = "capture_%s.log" % conversant
531         tlog("\nRecording session %s as %s." % (conversant, logfile))
532         log = open(logfile, "w")
533         log.write(captures[conversant])
534         log.close()
535     if not stop_service(service):
536         success = False
537     tlog("\nRan %s tests in %.3f seconds." % (len(dialogue), duration))
538     if success:
539         tlog("\nSUCCESS\n")
540     else:
541         tlog("\nFAILURE\n")
542         sys.exit(1)
543
544
545 if __name__ == '__main__':
546     sys.exit(main())