blob: 77ca294306eee2593560638856197be484a3b305 [file] [log] [blame]
Nick Coghlan029ba2b2011-08-22 16:05:44 +10001import mailcap
2import os
3import shutil
4import test.support
5import unittest
6
7# Location of mailcap file
8MAILCAPFILE = test.support.findfile("mailcap.txt")
9
10# Dict to act as mock mailcap entry for this test
11# The keys and values should match the contents of MAILCAPFILE
12MAILCAPDICT = {'application/x-movie': [{'compose': 'moviemaker %s',
13 'x11-bitmap': '"/usr/lib/Zmail/bitmaps/movie.xbm"',
14 'description': '"Movie"',
15 'view': 'movieplayer %s'}],
16 'application/*': [{'copiousoutput': '',
17 'view': 'echo "This is \\"%t\\" but is 50 \\% Greek to me" \\; cat %s'}],
18 'audio/basic': [{'edit': 'audiocompose %s',
19 'compose': 'audiocompose %s',
20 'description': '"An audio fragment"',
21 'view': 'showaudio %s'}],
22 'video/mpeg': [{'view': 'mpeg_play %s'}],
23 'application/postscript': [{'needsterminal': '',
24 'view': 'ps-to-terminal %s'},
25 {'compose': 'idraw %s',
26 'view': 'ps-to-terminal %s'}],
27 'application/x-dvi': [{'view': 'xdvi %s'}],
28 'message/external-body': [{'composetyped': 'extcompose %s',
29 'description': '"A reference to data stored in an external location"',
30 'needsterminal': '',
31 'view': 'showexternal %s %{access-type} %{name} %{site} %{directory} %{mode} %{server}'}],
32 'text/richtext': [{'test': 'test "`echo %{charset} | tr \'[A-Z]\' \'[a-z]\'`" = iso-8859-8',
33 'copiousoutput': '',
34 'view': 'shownonascii iso-8859-8 -e richtext -p %s'}],
35 'image/x-xwindowdump': [{'view': 'display %s'}],
36 'audio/*': [{'view': '/usr/local/bin/showaudio %t'}],
37 'video/*': [{'view': 'animate %s'}],
38 'application/frame': [{'print': '"cat %s | lp"',
39 'view': 'showframe %s'}],
40 'image/rgb': [{'view': 'display %s'}]}
41
42
43class HelperFunctionTest(unittest.TestCase):
44
45 def test_listmailcapfiles(self):
46 # The return value for listmailcapfiles() will vary by system.
47 # So verify that listmailcapfiles() returns a list of strings that is of
48 # non-zero length.
49 mcfiles = mailcap.listmailcapfiles()
50 self.assertTrue(isinstance(mcfiles, list))
51 self.assertTrue(all([isinstance(m, str) for m in mcfiles]))
52 with test.support.EnvironmentVarGuard() as env:
53 # According to RFC 1524, if MAILCAPS env variable exists, use that
54 # and only that.
55 if "MAILCAPS" in env:
56 env_mailcaps = env["MAILCAPS"].split(os.pathsep)
57 else:
58 env_mailcaps = ["/testdir1/.mailcap", "/testdir2/mailcap"]
59 env["MAILCAPS"] = os.pathsep.join(env_mailcaps)
60 mcfiles = mailcap.listmailcapfiles()
61 self.assertEqual(env_mailcaps, mcfiles)
62
63 def test_readmailcapfile(self):
64 # Test readmailcapfile() using test file. It should match MAILCAPDICT.
65 with open(MAILCAPFILE, 'r') as mcf:
66 d = mailcap.readmailcapfile(mcf)
67 self.assertDictEqual(d, MAILCAPDICT)
68
69 def test_lookup(self):
70 # Test without key
71 expected = [{'view': 'mpeg_play %s'}, {'view': 'animate %s'}]
72 actual = mailcap.lookup(MAILCAPDICT, 'video/mpeg')
73 self.assertListEqual(expected, actual)
74
75 # Test with key
76 key = 'compose'
77 expected = [{'edit': 'audiocompose %s',
78 'compose': 'audiocompose %s',
79 'description': '"An audio fragment"',
80 'view': 'showaudio %s'}]
81 actual = mailcap.lookup(MAILCAPDICT, 'audio/basic', key)
82 self.assertListEqual(expected, actual)
83
84 def test_subst(self):
85 plist = ['id=1', 'number=2', 'total=3']
86 # test case: ([field, MIMEtype, filename, plist=[]], <expected string>)
87 test_cases = [
88 (["", "audio/*", "foo.txt"], ""),
89 (["echo foo", "audio/*", "foo.txt"], "echo foo"),
90 (["echo %s", "audio/*", "foo.txt"], "echo foo.txt"),
91 (["echo %t", "audio/*", "foo.txt"], "echo audio/*"),
92 (["echo \%t", "audio/*", "foo.txt"], "echo %t"),
93 (["echo foo", "audio/*", "foo.txt", plist], "echo foo"),
94 (["echo %{total}", "audio/*", "foo.txt", plist], "echo 3")
95 ]
96 for tc in test_cases:
97 self.assertEqual(mailcap.subst(*tc[0]), tc[1])
98
99
100class GetcapsTest(unittest.TestCase):
101
102 def test_mock_getcaps(self):
103 # Test mailcap.getcaps() using mock mailcap file in this dir.
104 # Temporarily override any existing system mailcap file by pointing the
105 # MAILCAPS environment variable to our mock file.
106 with test.support.EnvironmentVarGuard() as env:
107 env["MAILCAPS"] = MAILCAPFILE
108 caps = mailcap.getcaps()
109 self.assertDictEqual(caps, MAILCAPDICT)
110
111 def test_system_mailcap(self):
112 # Test mailcap.getcaps() with mailcap file(s) on system, if any.
113 caps = mailcap.getcaps()
114 self.assertTrue(isinstance(caps, dict))
115 mailcapfiles = mailcap.listmailcapfiles()
116 existingmcfiles = [mcf for mcf in mailcapfiles if os.path.exists(mcf)]
117 if existingmcfiles:
118 # At least 1 mailcap file exists, so test that.
119 for (k, v) in caps.items():
120 self.assertTrue(isinstance(k, str))
121 self.assertTrue(isinstance(v, list))
122 self.assertTrue(all([isinstance(e, dict) for e in v]))
123 else:
124 # No mailcap files on system. getcaps() should return empty dict.
125 self.assertEqual({}, caps)
126
127
128class FindmatchTest(unittest.TestCase):
129
130 def test_findmatch(self):
131
132 # default findmatch arguments
133 c = MAILCAPDICT
134 fname = "foo.txt"
135 plist = ["access-type=default", "name=john", "site=python.org",
136 "directory=/tmp", "mode=foo", "server=bar"]
137 audio_basic_entry = {'edit': 'audiocompose %s',
138 'compose': 'audiocompose %s',
139 'description': '"An audio fragment"',
140 'view': 'showaudio %s'}
141 audio_entry = {"view": "/usr/local/bin/showaudio %t"}
142 video_entry = {'view': 'animate %s'}
143 message_entry = {'composetyped': 'extcompose %s',
144 'description': '"A reference to data stored in an external location"', 'needsterminal': '',
145 'view': 'showexternal %s %{access-type} %{name} %{site} %{directory} %{mode} %{server}'}
146
147 # test case: (findmatch args, findmatch keyword args, expected output)
148 # positional args: caps, MIMEtype
149 # keyword args: key="view", filename="/dev/null", plist=[]
150 # output: (command line, mailcap entry)
151 cases = [
152 ([{}, "video/mpeg"], {}, (None, None)),
153 ([c, "foo/bar"], {}, (None, None)),
154 ([c, "video/mpeg"], {}, ('mpeg_play /dev/null', {'view': 'mpeg_play %s'})),
155 ([c, "audio/basic", "edit"], {}, ("audiocompose /dev/null", audio_basic_entry)),
156 ([c, "audio/basic", "compose"], {}, ("audiocompose /dev/null", audio_basic_entry)),
157 ([c, "audio/basic", "description"], {}, ('"An audio fragment"', audio_basic_entry)),
158 ([c, "audio/basic", "foobar"], {}, (None, None)),
159 ([c, "video/*"], {"filename": fname}, ("animate %s" % fname, video_entry)),
160 ([c, "audio/basic", "compose"],
161 {"filename": fname},
162 ("audiocompose %s" % fname, audio_basic_entry)),
163 ([c, "audio/basic"],
164 {"key": "description", "filename": fname},
165 ('"An audio fragment"', audio_basic_entry)),
166 ([c, "audio/*"],
167 {"filename": fname},
168 ("/usr/local/bin/showaudio audio/*", audio_entry)),
169 ([c, "message/external-body"],
170 {"plist": plist},
171 ("showexternal /dev/null default john python.org /tmp foo bar", message_entry))
172 ]
173 self._run_cases(cases)
174
175 @unittest.skipUnless(os.name == "posix", "Requires 'test' command on system")
176 def test_test(self):
177 # findmatch() will automatically check any "test" conditions and skip
178 # the entry if the check fails.
179 caps = {"test/pass": [{"test": "test 1 -eq 1"}],
180 "test/fail": [{"test": "test 1 -eq 0"}]}
181 # test case: (findmatch args, findmatch keyword args, expected output)
182 # positional args: caps, MIMEtype, key ("test")
183 # keyword args: N/A
184 # output: (command line, mailcap entry)
185 cases = [
186 # findmatch will return the mailcap entry for test/pass because it evaluates to true
187 ([caps, "test/pass", "test"], {}, ("test 1 -eq 1", {"test": "test 1 -eq 1"})),
188 # findmatch will return None because test/fail evaluates to false
189 ([caps, "test/fail", "test"], {}, (None, None))
190 ]
191 self._run_cases(cases)
192
193 def _run_cases(self, cases):
194 for c in cases:
195 self.assertEqual(mailcap.findmatch(*c[0], **c[1]), c[2])
196
197
198def test_main():
199 test.support.run_unittest(HelperFunctionTest, GetcapsTest, FindmatchTest)
200
201
202if __name__ == '__main__':
203 test_main()