1 # Copyright (c) 2004-2020 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.
16 # TODO(fungi) Clean this up once Python 3.5 is no longer supported
17 if sys.version < "3.6":
19 odict = collections.OrderedDict
23 pidfile = "var/mudpy.pid"
25 test_account0_setup = (
26 (0, "Identify yourself:", "luser0"),
27 (0, "Enter your choice:", "n"),
28 (0, 'Enter a new password for "luser0":', "Test123"),
29 (0, "Enter the same new password again:", "Test123"),
30 (0, r"What would you like to do\?", "c"),
31 (0, "Pick a birth gender for your new avatar:", "f"),
32 (0, "Choose a name for her:", "1"),
33 (0, r"What would you like to do\?", "a"),
34 (0, r"Whom would you like to awaken\?", ""),
37 test_account1_setup = (
38 (1, "Identify yourself:", "luser1"),
39 (1, "Enter your choice:", "n"),
40 (1, 'Enter a new password for "luser1":', "Test456"),
41 (1, "Enter the same new password again:", "Test456"),
42 (1, r"What would you like to do\?", "c"),
43 (1, "Pick a birth gender for your new avatar:", "m"),
44 (1, "Choose a name for him:", "1"),
45 (1, r"What would you like to do\?", "a"),
46 (1, r"Whom would you like to awaken\?", ""),
49 test_actor_appears = (
50 (0, r"You suddenly realize that .* is here\.", ""),
53 test_explicit_punctuation = (
54 (0, "> ", "say Hello there!"),
55 (0, r'You exclaim, "Hello there\!"', ""),
56 (1, r'exclaims, "Hello there\!"', "say And you are?"),
57 (1, r'You ask, "And you are\?"', ""),
58 (0, r'asks, "And you are\?"', "say I'm me, of course."),
59 (0, r'''You say, "I'm me, of course\."''', ""),
60 (1, r'''says, "I'm me, of course\."''', "say I wouldn't be so sure..."),
61 (1, r'''You muse, "I wouldn't be so sure\.\.\."''', ""),
62 (0, r'''muses, "I wouldn't be so sure\.\.\."''', "say You mean,"),
63 (0, 'You begin, "You mean,"', ""),
64 (1, 'begins, "You mean,"', "say I know-"),
65 (1, 'You begin, "I know-"', ""),
66 (0, 'begins, "I know-"', "say Don't interrupt:"),
67 (0, r'''You begin, "Don't interrupt:"''', ""),
68 (1, r'''begins, "Don't interrupt:"''', "say I wasn't interrupting;"),
69 (1, r'''You begin, "I wasn't interrupting;"''', ""),
70 (0, r'''begins, "I wasn't interrupting;"''', ""),
73 test_implicit_punctuation = (
74 (0, '> ', "say Whatever"),
75 (0, r'You say, "Whatever\."', ""),
76 (1, r'says, "Whatever\."', ""),
79 test_typo_replacement = (
80 (1, '> ', "say That's what i think."),
81 (1, r'''You say, "That's what I think\."''', ""),
82 (0, r'''says, "That's what I think\."''', "say You know what i'd like."),
83 (0, r'''You say, "You know what I'd like\."''', ""),
84 (1, r'''says, "You know what I'd like\."''', "say Then i'll tell you."),
85 (1, r'''You say, "Then I'll tell you\."''', ""),
86 (0, r'''says, "Then I'll tell you\."''', "say Now i'm ready."),
87 (0, r'''You say, "Now I'm ready\."''', ""),
88 (1, r'''says, "Now I'm ready\."''', "say That's teh idea."),
89 (1, r'''You say, "That's the idea\."''', ""),
90 (0, r'''says, "That's the idea\."''', "say It's what theyre saying."),
91 (0, r'''You say, "It's what they're saying\."''', ""),
92 (1, r'''says, "It's what they're saying\."''', "say Well, youre right."),
93 (1, r'''You say, "Well, you're right\."''', ""),
94 (0, r'''says, "Well, you're right\."''', ""),
97 test_sentence_capitalization = (
98 (0, "> ", "say this sentence should start with a capital T."),
99 (0, 'You say, "This sentence', ""),
100 (1, 'says, "This sentence', ""),
105 (1, r'(?s)Entering chat mode .*> \(chat\) ', "Feeling chatty."),
106 (1, r'You say, "Feeling chatty\."', "!chat"),
107 (0, r'says, "Feeling chatty\."', ""),
108 (1, '> ', "say Now less chatty."),
109 (1, r'You say, "Now less chatty\."', ""),
110 (0, r'says, "Now less chatty\."', ""),
114 (0, '> ', "say " + 100 * "o"),
115 (1, r'says,\r\n"O[o]+\."', ""),
118 test_forbid_ansi_input = (
119 (0, '> ', "say \x1b[35mfoo\x1b[0m"),
120 (1, r'says, "\[35mfoo\[0m\."', ""),
123 test_escape_macros = (
124 (0, '> ', "say $(red)bar$(nrm)"),
125 (1, r'says, "\$\(red\)bar\$\(nrm\)\."', ""),
129 (0, "> ", "move north"),
130 (0, r"You exit to the north\.", ""),
131 (1, r"exits to the north\.", "move north"),
132 (0, r"arrives from the south\.", "move south"),
133 (0, r"You exit to the south\.", ""),
134 (1, r"exits to the south\.", "move south"),
135 (0, r"arrives from the north\.", "move east"),
136 (0, r"You exit to the east\.", ""),
137 (1, r"exits to the east\.", "move east"),
138 (0, r"arrives from the west\.", "move west"),
139 (0, r"You exit to the west\.", ""),
140 (1, r"exits to the west\.", "move west"),
141 (0, r"arrives from the east\.", "move up"),
142 (0, r"You exit upward\.", ""),
143 (1, r"exits upward\.", "move up"),
144 (0, r"arrives from below\.", "move down"),
145 (0, r"You exit downward\.", ""),
146 (1, r"exits downward\.", "move down"),
147 (0, r"arrives from above\.", ""),
150 test_actor_disappears = (
152 (0, r"You suddenly wonder where .* went\.", ""),
155 test_abort_avatar_deletion = (
156 (1, r"What would you like to do\?", "d"),
157 (1, r"Whom would you like to delete\?", ""),
158 (1, r"delete an unwanted avatar.*What would you like to do\?", ""),
161 test_avatar_creation_limit = (
162 (1, r"What would you like to do\?", "c"),
163 (1, "Pick a birth gender for your new avatar:", "m"),
164 (1, "Choose a name for him:", "3"),
165 (1, r"What would you like to do\?", "c"),
166 (1, "Pick a birth gender for your new avatar:", "m"),
167 (1, "Choose a name for him:", "4"),
168 (1, r"What would you like to do\?", "c"),
169 (1, "Pick a birth gender for your new avatar:", "m"),
170 (1, "Choose a name for him:", "7"),
171 (1, r"What would you like to do\?", "c"),
172 (1, "Pick a birth gender for your new avatar:", "m"),
173 (1, "Choose a name for him:", "5"),
174 (1, r"What would you like to do\?", "c"),
175 (1, "Pick a birth gender for your new avatar:", "m"),
176 (1, "Choose a name for him:", "2"),
177 (1, r"What would you like to do\?", "c"),
178 (1, "Pick a birth gender for your new avatar:", "m"),
179 (1, "Choose a name for him:", "6"),
180 (1, r"What would you like to do\?", "c"),
181 (1, r"That is not a valid choice\.\.\.", ""),
184 test_avatar_deletion = (
185 (1, r"What would you like to do\?", "d"),
186 (1, r"Whom would you like to delete\?", "1"),
187 (1, r"create a new avatar.*What would you like to do\?", ""),
190 test_abort_account_deletion = (
191 (1, r"What would you like to do\?", "p"),
192 (1, r"permanently delete your account\?", ""),
193 (1, r"What would you like to do\?", ""),
196 test_account_deletion = (
197 (1, r"What would you like to do\?", "p"),
198 (1, r"permanently delete your account\?", "y"),
199 (1, r"Disconnecting\.\.\.", ""),
203 (2, "Identify yourself:", "admin"),
204 (2, "Enter your choice:", "n"),
205 (2, 'Enter a new password for "admin":', "Test789"),
206 (2, "Enter the same new password again:", "Test789"),
207 (2, r"What would you like to do\?", "c"),
208 (2, "Pick a birth gender for your new avatar:", "m"),
209 (2, "Choose a name for him:", "1"),
210 (2, r"What would you like to do\?", "a"),
211 (2, r"Whom would you like to awaken\?", ""),
215 (0, "> ", "preferences"),
216 (0, r"\[32mprompt\x1b\[0m - <not set>.*> ", "preferences prompt $(foo)"),
217 (0, r"\$\(foo\) ", "preferences prompt"),
218 (0, r"\$\(foo\).*\$\(foo\) ", "preferences prompt $(time)>"),
219 (0, "[0-9]> ", "preferences loglevel 0"),
220 (0, "does not exist.*> ", "preferences prompt >"),
221 (2, "> ", "preferences loglevel 0"),
222 (2, "> ", "preferences"),
223 (2, r"\[31mloglevel\x1b\[0m - 0.*> ", "preferences loglevel zero"),
224 (2, r'''cannot be set to type "<class 'str'>"\..*> ''', ""),
228 # Send a CR+LF at the end of the line instead of the default CR+NUL,
229 # to make sure they're treated the same
230 (2, "> ", b"say I use CR+LF as my EOL, not CR+NUL.\r\n"),
231 (2, r'You say, "I use CR\+LF as my EOL, not CR\+NUL\.".*> ', ""),
235 # Send a double (escaped) IAC byte within other text, which should get
236 # unescaped and deduplicated to a single \xff in the buffer and then
237 # the line of input discarded as a non-ASCII sequence
238 (2, "> ", b"say argle\xff\xffbargle\r\0"),
239 (2, r"Non-ASCII characters from admin: b'say.*argle\\xffbargle'.*> ", ""),
242 test_telnet_unknown_command = (
243 # Send an unsupported negotiation command #127 which should get filtered
244 # from the line of input
245 (2, "> ", b"say glop\xff\x7fglyf\r\0"),
246 (2, r'Ignored unknown command 127 from admin\..*"Glopglyf\.".*> ', ""),
249 test_telnet_unknown_option = (
250 # Send an unassigned negotiation option #127 which should get logged
251 (2, "> ", b"\xff\xfe\x7f\r\0"),
252 (2, r'''Received "don't 127" from admin\..*> ''', ""),
255 test_admin_restriction = (
256 (0, "> ", "help halt"),
257 (0, r"That is not an available command\.", "halt"),
258 (0, '(not sure what "halt" means|Arglebargle, glop-glyf)', ""),
263 (2, r"halt.*Shut down the world\.", "help halt"),
264 (2, "This will save all active accounts", ""),
268 (0, "> ", "help say"),
269 (0, r"See also: .*chat.*> ", ""),
274 (0, r"h\[elp\].*m\[ove\].*> ", "he mo"),
275 (0, r"Move in a specific direction\..*> ", "mov nor"),
276 (0, r"You exit to the north\..*> ", "m s"),
277 (0, r"You exit to the south\..*> ", ""),
282 (2, r"Reloading all code modules, configs and data\."
283 r".* User admin reloaded the world\.",
284 "show element account.admin"),
285 (2, r'These are the properties of the "account\.admin" element.*'
286 r' \x1b\[32mpasshash:\r\n\x1b\[31m\$.*> ', ""),
290 (2, "> ", "set actor.avatar_admin_0 gender female"),
291 (2, r'You have successfully \(re\)set the "gender" facet of element', ""),
295 (2, "> ", "set mudpy.limit password_tries 10"),
296 (2, r'The "mudpy\.limit" element is kept in read-only file', ""),
299 test_show_version = (
300 (2, "> ", "show version"),
301 (2, r"Running mudpy .* on .* Python 3.*with.*pyyaml.*> ", ""),
305 (2, "> ", "show time"),
306 (2, r"\r\n[0-9]+ increments elapsed.*> ", ""),
310 (2, "> ", "show files"),
311 (2, r'These are the current files containing the universe:.*'
312 r' \x1b\[31m\(rw\) \x1b\[32m/.*/account\.yaml\x1b\[0m'
313 r' \x1b\[33m\[private\]\x1b\[0m.*> ', ""),
317 (2, "> ", "show file %s" %
318 os.path.join(os.getcwd(), "data/internal.yaml")),
319 (2, r'These are the nodes in the.*file:.*internal\.counters.*> ', ""),
323 (2, "> ", "show groups"),
324 (2, r'These are the element groups:.*'
325 r' \x1b\[32maccount\x1b\[0m.*> ', ""),
329 (2, "> ", "show group account"),
330 (2, r'These are the elements in the "account" group:.*'
331 r' \x1b\[32maccount\.admin\x1b\[0m.*> ', ""),
334 test_show_element = (
335 (2, "> ", "show element mudpy.limit"),
336 (2, r'These are the properties of the "mudpy\.limit" element.*'
337 r' \x1b\[32mpassword_tries: \x1b\[31m3.*> ',
338 "show element actor.avatar_admin_0"),
339 (2, r'These are the properties of the "actor\.avatar_admin_0" element.*'
340 r' \x1b\[32mgender: \x1b\[31mfemale.*> ', ""),
344 (2, "> ", "show result 12345*67890"),
345 (2, r"\r\n838102050\r\n.*> ", "show result 1/0"),
346 (2, r"Your expression raised an exception.*division by zero.*> ",
347 "show result mudpy"),
348 (2, r"<module 'mudpy' from.*> ", "show result re"),
349 (2, r"Your expression raised an exception.*name 're' is not defined.*> ",
350 "show result universe"),
351 (2, r"<mudpy\.misc\.Universe object at 0x.*> ", "show result actor"),
352 (2, r"Your expression raised an exception.*name 'actor' is not "
357 (2, "> ", "show log"),
358 (2, r"There are [0-9]+ log lines in memory and [0-9]+ at or above level "
359 r"[0-9]+\. The matching.*from [0-9]+ to [0-9]+ are:", ""),
362 test_custom_loglevel = (
363 (2, "> ", "set account.admin loglevel 2"),
364 (2, "You have successfully .*> ", "show log"),
365 (2, r"There are [0-9]+ log lines in memory and [0-9]+ at or above level "
366 r"[0-9]+\. The matching.*from [0-9]+ to [0-9]+ are:", ""),
369 test_invalid_loglevel = (
370 (2, "> ", "set account.admin loglevel two"),
371 (2, r'''Value "two" of type "<class 'str'>" cannot be coerced .*> ''', ""),
374 test_log_no_errors = (
375 (2, "> ", "show log 7"),
376 (2, r"None of the [0-9]+ lines in memory matches your request\.", ""),
381 (0, r"What would you like to do\?", "p"),
382 (0, r"permanently delete your account\?", "y"),
383 (0, r"Disconnecting\.\.\.", ""),
385 (2, r"What would you like to do\?", "p"),
386 (2, r"permanently delete your account\?", "y"),
387 (2, r"Disconnecting\.\.\.", ""),
391 (test_account0_setup, "first account setup"),
392 (test_account1_setup, "second account setup"),
393 (test_actor_appears, "actor spontaneous appearance"),
394 (test_explicit_punctuation, "explicit punctuation"),
395 (test_implicit_punctuation, "implicit punctuation"),
396 (test_typo_replacement, "typo replacement"),
397 (test_sentence_capitalization, "sentence capitalization"),
398 (test_chat_mode, "chat mode"),
399 (test_wrapping, "wrapping"),
400 (test_forbid_ansi_input, "raw escape input is filtered"),
401 (test_escape_macros, "replacement macros are escaped"),
402 (test_movement, "movement"),
403 (test_actor_disappears, "actor spontaneous disappearance"),
404 (test_abort_avatar_deletion, "abort avatar deletion"),
405 (test_avatar_creation_limit, "avatar creation limit"),
406 (test_avatar_deletion, "avatar deletion"),
407 (test_abort_account_deletion, "abort account deletion"),
408 (test_account_deletion, "account deletion"),
409 (test_admin_setup, "admin account setup"),
410 (test_preferences, "set and show preferences"),
411 (test_crlf_eol, "send crlf from the client as eol"),
412 (test_telnet_iac, "escape stray telnet iac bytes"),
413 (test_telnet_unknown_command, "strip unknown telnet command"),
414 (test_telnet_unknown_option, "log unknown telnet option"),
415 (test_admin_restriction, "restricted admin commands"),
416 (test_admin_help, "admin help"),
417 (test_help, "help command"),
418 (test_abbrev, "command abbreviation"),
419 (test_reload, "reload"),
420 (test_set_facet, "set facet"),
421 (test_set_refused, "refuse altering read-only element"),
422 (test_show_version, "show version and diagnostic info"),
423 (test_show_time, "show elapsed world clock increments"),
424 (test_show_files, "show a list of loaded files"),
425 (test_show_file, "show nodes from a specific file"),
426 (test_show_groups, "show groups"),
427 (test_show_group, "show group"),
428 (test_show_element, "show element"),
429 (test_show_result, "show result of a python expression"),
430 (test_show_log, "show log"),
431 (test_custom_loglevel, "custom loglevel"),
432 (test_invalid_loglevel, "invalid loglevel"),
433 (test_log_no_errors, "no errors logged"),
434 (final_cleanup, "delete remaining accounts"),
444 def start_service(config):
445 # Clean up any previously run daemon which didn't terminate
446 if os.path.exists(pidfile):
447 with open(pidfile) as pidfd:
448 pid = int(pidfd.read())
450 # Stop the running service
453 except ProcessLookupError:
454 # If there was no process, just remove the stale PID file
456 # If there's a preexisting hung service, we can't proceed
457 assert not os.path.exists(pidfile)
459 # Clean up any previous test output
460 for f in pathlib.Path(".").glob("capture_*.log"):
461 # have to use .name here since remove() doesn't support passing a
462 # PosixPath argument until Python3.6
464 for d in ("data", "var"):
465 shutil.rmtree(d, ignore_errors=True)
467 # Start the service and wait for it to be ready for connections
468 service = subprocess.Popen(("mudpy", config),
469 stdout=subprocess.PIPE,
470 stderr=subprocess.PIPE)
475 def stop_service(service):
478 # The no-op case when no service was started
482 # This handles when the service is running as a direct child process
484 returncode = service.wait(10)
486 tlog("\nERROR: Service exited with code %s." % returncode)
489 # This cleans up a daemonized and disassociated service
490 if os.path.exists(pidfile):
491 with open(pidfile) as pidfd:
492 pid = int(pidfd.read())
494 # Stop the running service
497 except ProcessLookupError:
498 # If there was no process, just remove the stale PID file
500 # The PID file didn't disappear, so we have a hung service
501 if os.path.exists(pidfile):
502 tlog("\nERROR: Hung daemon with PID %s." % pid)
505 # Log the contents of stdout and stderr, if any
506 stdout, stderr = service.communicate()
507 tlog("\nRecording stdout as capture_stdout.log.")
508 with open("capture_stdout.log", "w") as serviceout:
509 serviceout.write(stdout.decode("utf-8"))
510 tlog("\nRecording stderr as capture_stderr.log.")
511 with open("capture_stderr.log", "w") as serviceerr:
512 serviceerr.write(stderr.decode("utf-8"))
517 def tlog(message, quiet=False):
518 logfile = "capture_tests.log"
519 with open(logfile, "a") as logfd:
520 logfd.write(message + "\n")
522 sys.stdout.write(message)
526 def option_callback(telnet_socket, command, option):
527 if option == b'\x7f':
528 # We use this unassigned option value as a canary, so short-circuit
529 # any response to avoid endlessly looping
531 elif command in (telnetlib.DO, telnetlib.DONT):
532 telnet_socket.send(telnetlib.IAC + telnetlib.WONT + option)
533 elif command in (telnetlib.WILL, telnetlib.WONT):
534 telnet_socket.send(telnetlib.IAC + telnetlib.DONT + option)
538 if len(sys.argv) > 1:
539 config = yaml.safe_load(open(sys.argv[1]))
540 return config.get(".mudpy.limit.debug", False)
545 captures = ["", "", ""]
546 lusers = [telnetlib.Telnet(), telnetlib.Telnet(), telnetlib.Telnet()]
550 if len(sys.argv) > 1:
551 # Start the service if a config file was provided on the command line
552 service = start_service(sys.argv[1])
554 tlog("\nERROR: Service did not start.\n")
557 luser.open("::1", 4000)
558 luser.set_option_negotiation_callback(option_callback)
559 selected_dialogue = odict(dialogue)
561 for test in nondebug_tests:
562 del selected_dialogue[test]
564 for test in debug_tests:
565 del selected_dialogue[test]
566 for test, description in selected_dialogue.items():
567 tlog("\nTesting %s..." % description)
568 test_start = time.time()
569 for conversant, question, answer in test:
570 tlog("luser%s waiting for: %s" % (conversant, question),
573 index, match, received = lusers[conversant].expect(
574 [re.compile(question.encode("utf-8"), flags=re.DOTALL)], 5)
575 captures[conversant] += received.decode("utf-8")
576 except ConnectionResetError:
577 tlog("\nERROR: Unable to connect to server.")
581 tlog("\nERROR: luser%s premature disconnection expecting:\n\n"
583 "Check the end of capture_%s.log for received data."
584 % (conversant, question, conversant))
588 captures[conversant] += lusers[
589 conversant].read_very_eager().decode("utf-8")
593 tlog("\nERROR: luser%s did not receive expected string:\n\n"
595 "Check the end of capture_%s.log for received data."
596 % (conversant, question, conversant))
599 if type(answer) is str:
600 tlog("luser%s sending: %s" % (conversant, answer), quiet=True)
601 lusers[conversant].write(("%s\r\0" % answer).encode("utf-8"))
602 captures[conversant] += "%s\r\n" % answer
603 elif type(answer) is bytes:
604 tlog("luser%s sending raw bytes: %s" % (conversant, answer),
606 lusers[conversant].get_socket().send(answer)
607 captures[conversant] += "!!!RAW BYTES: %s" % answer
609 tlog("\nERROR: answer provided with unsupported type %s"
615 tlog("Completed in %.3f seconds." % (time.time() - test_start))
616 duration = time.time() - start
617 for conversant in range(len(captures)):
619 captures[conversant] += lusers[
620 conversant].read_very_eager().decode("utf-8")
623 lusers[conversant].close()
624 logfile = "capture_%s.log" % conversant
625 tlog("\nRecording session %s as %s." % (conversant, logfile))
626 log = open(logfile, "w")
627 log.write(captures[conversant])
629 if not stop_service(service):
631 tlog("\nRan %s tests in %.3f seconds." % (len(dialogue), duration))
639 if __name__ == '__main__':