test_win32inet.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from win32inet import *
  2. from win32inetcon import *
  3. import winerror
  4. from pywin32_testutil import str2bytes # py3k-friendly helper
  5. from pywin32_testutil import TestSkipped
  6. import unittest
  7. class CookieTests(unittest.TestCase):
  8. def testCookies(self):
  9. data = "TestData=Test"
  10. InternetSetCookie("http://www.python.org", None, data)
  11. got = InternetGetCookie("http://www.python.org", None)
  12. self.assertEqual(got, data)
  13. def testCookiesEmpty(self):
  14. try:
  15. InternetGetCookie("http://site-with-no-cookie.python.org", None)
  16. self.fail("expected win32 exception")
  17. except error as exc:
  18. self.failUnlessEqual(exc.winerror, winerror.ERROR_NO_MORE_ITEMS)
  19. class UrlTests(unittest.TestCase):
  20. def testSimpleCanonicalize(self):
  21. ret = InternetCanonicalizeUrl("foo bar")
  22. self.assertEqual(ret, "foo%20bar")
  23. def testLongCanonicalize(self):
  24. # a 4k URL causes the underlying API to request a bigger buffer"
  25. big = "x" * 2048
  26. ret = InternetCanonicalizeUrl(big + " " + big)
  27. self.assertEqual(ret, big + "%20" + big)
  28. class TestNetwork(unittest.TestCase):
  29. def setUp(self):
  30. self.hi = InternetOpen("test", INTERNET_OPEN_TYPE_DIRECT, None, None, 0)
  31. def tearDown(self):
  32. self.hi.Close()
  33. def testPythonDotOrg(self):
  34. hdl = InternetOpenUrl(self.hi, "http://www.python.org", None,
  35. INTERNET_FLAG_EXISTING_CONNECT)
  36. chunks = []
  37. while 1:
  38. chunk = InternetReadFile(hdl, 1024)
  39. if not chunk:
  40. break
  41. chunks.append(chunk)
  42. data = str2bytes('').join(chunks)
  43. assert data.find(str2bytes("Python"))>0, repr(data) # This must appear somewhere on the main page!
  44. def testFtpCommand(self):
  45. # ftp.python.org doesn't exist. ftp.gnu.org is what Python's urllib
  46. # test code uses.
  47. # (As of 2020 it doesn't! Unsurprisingly, it's difficult to find a good
  48. # test server. This test sometimes works, but often doesn't - so handle
  49. # failure here as a "skip")
  50. try:
  51. hcon = InternetConnect(self.hi, "ftp.gnu.org", INTERNET_INVALID_PORT_NUMBER,
  52. None, None, # username/password
  53. INTERNET_SERVICE_FTP, 0, 0)
  54. try:
  55. hftp = FtpCommand(hcon, True, FTP_TRANSFER_TYPE_ASCII, 'NLST', 0)
  56. try:
  57. print("Connected - response info is", InternetGetLastResponseInfo())
  58. got = InternetReadFile(hftp, 2048)
  59. print("Read", len(got), "bytes")
  60. finally:
  61. hftp.Close()
  62. finally:
  63. hcon.Close()
  64. except error as e:
  65. raise TestSkipped(e)
  66. if __name__=='__main__':
  67. unittest.main()