Advertisement
Guest User

HTTP Error Body Test for OpenComputers

a guest
Jun 15th, 2025
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 12.29 KB | Source Code | 0 0
  1. -- HTTP Error Body Test for OpenComputers
  2. -- Tests the new allowErrorBody parameter in internet.request()
  3.  
  4. local internet = require("internet")
  5. local component = require("component")
  6.  
  7. -- ANSI colors for beautiful output
  8. local colors = {
  9.   reset = "\27[0m",
  10.   bold = "\27[1m",
  11.   red = "\27[31m",
  12.   green = "\27[32m",
  13.   yellow = "\27[33m",
  14.   blue = "\27[34m",
  15.   magenta = "\27[35m",
  16.   cyan = "\27[36m",
  17.   white = "\27[37m",
  18.   bg_red = "\27[41m",
  19.   bg_green = "\27[42m",
  20.   bg_blue = "\27[44m"
  21. }
  22.  
  23. -- Functions for colored output
  24. local function colorPrint(color, text)
  25.   print(color .. text .. colors.reset)
  26. end
  27.  
  28. local function successPrint(text)
  29.   colorPrint(colors.green .. colors.bold, "✅ " .. text)
  30. end
  31.  
  32. local function errorPrint(text)
  33.   colorPrint(colors.red .. colors.bold, "❌ " .. text)
  34. end
  35.  
  36. local function warningPrint(text)
  37.   colorPrint(colors.yellow .. colors.bold, "⚠️  " .. text)
  38. end
  39.  
  40. local function infoPrint(text)
  41.   colorPrint(colors.cyan, "ℹ️  " .. text)
  42. end
  43.  
  44. local function headerPrint(text)
  45.   print()
  46.   colorPrint(colors.blue .. colors.bold, "═══ " .. text .. " ═══")
  47.   print()
  48. end
  49.  
  50. -- Check for internet card availability
  51. if not component.isAvailable("internet") then
  52.   errorPrint("Internet card not found!")
  53.   return
  54. end
  55.  
  56. -- Beautiful header
  57. print()
  58. colorPrint(colors.bg_blue .. colors.white .. colors.bold, "                                                    ")
  59. colorPrint(colors.bg_blue .. colors.white .. colors.bold, "          HTTP ERROR BODY TEST v2.0                ")
  60. colorPrint(colors.bg_blue .. colors.white .. colors.bold, "      Testing allowErrorBody parameter             ")
  61. colorPrint(colors.bg_blue .. colors.white .. colors.bold, "                                                    ")
  62. print()
  63.  
  64. infoPrint("Testing new allowErrorBody parameter in internet.request()")
  65. infoPrint("Verifying backward compatibility and new functionality")
  66. print()
  67.  
  68. -- Test URLs with different HTTP codes
  69. local testUrls = {
  70.   -- 2xx Success
  71.   {url = "https://httpbin.org/status/200", code = 200, desc = "OK", category = "success"},
  72.   {url = "https://httpbin.org/status/201", code = 201, desc = "Created", category = "success"},
  73.   {url = "https://httpbin.org/status/202", code = 202, desc = "Accepted", category = "success"},
  74.  
  75.   -- 4xx Client Error (main ones for testing)
  76.   {url = "https://httpbin.org/status/400", code = 400, desc = "Bad Request", category = "client_error"},
  77.   {url = "https://httpbin.org/status/401", code = 401, desc = "Unauthorized", category = "client_error"},
  78.   {url = "https://httpbin.org/status/403", code = 403, desc = "Forbidden", category = "client_error"},
  79.   {url = "https://httpbin.org/status/404", code = 404, desc = "Not Found", category = "client_error"},
  80.   {url = "https://httpbin.org/status/418", code = 418, desc = "I'm a teapot", category = "client_error"},
  81.  
  82.   -- 5xx Server Error
  83.   {url = "https://httpbin.org/status/500", code = 500, desc = "Internal Server Error", category = "server_error"},
  84.   {url = "https://httpbin.org/status/502", code = 502, desc = "Bad Gateway", category = "server_error"},
  85.   {url = "https://httpbin.org/status/503", code = 503, desc = "Service Unavailable", category = "server_error"}
  86. }
  87.  
  88. local function makeRequest(url, allowErrorBody)
  89.   -- Use direct component call
  90.   local inet = component.internet
  91.   local request = inet.request(url, nil, nil, nil, allowErrorBody)
  92.  
  93.   if not request then
  94.     return nil, "request failed"
  95.   end
  96.  
  97.   -- Wait for response
  98.   local timeout = 0
  99.   while not request.finishConnect() and timeout < 10 do
  100.     os.sleep(0.1)
  101.     timeout = timeout + 0.1
  102.   end
  103.  
  104.   if timeout >= 10 then
  105.     request:close()
  106.     return nil, "timeout"
  107.   end
  108.  
  109.   -- Read response
  110.   local response = ""
  111.   while true do
  112.     local chunk = request.read()
  113.     if not chunk then
  114.       break
  115.     elseif #chunk > 0 then
  116.       response = response .. chunk
  117.     else
  118.       os.sleep(0.05)
  119.     end
  120.   end
  121.  
  122.   -- Get response code
  123.   local code, message = request.response()
  124.   request:close()
  125.  
  126.   return {
  127.     code = code,
  128.     message = message,
  129.     body = response,
  130.     bodyLength = #response
  131.   }
  132. end
  133.  
  134. -- Test 1: Legacy behavior (allowErrorBody = false)
  135. headerPrint("TEST 1: Legacy behavior (allowErrorBody = false)")
  136. infoPrint("HTTP errors should throw exceptions")
  137. infoPrint("2xx codes should work normally")
  138.  
  139. local successCount = 0
  140. local totalCount = 0
  141.  
  142. for i, test in ipairs(testUrls) do
  143.   totalCount = totalCount + 1
  144.  
  145.   -- Colored output for different categories
  146.   local categoryColor = colors.white
  147.   if test.category == "success" then categoryColor = colors.green
  148.   elseif test.category == "redirect" then categoryColor = colors.yellow
  149.   elseif test.category == "client_error" then categoryColor = colors.red
  150.   elseif test.category == "server_error" then categoryColor = colors.magenta
  151.   end
  152.  
  153.   colorPrint(colors.cyan, string.format("   🔍 Test %d: %s", i, test.url))
  154.   colorPrint(categoryColor, string.format("      📊 %d %s [%s]", test.code, test.desc, test.category))
  155.  
  156.   local success, result = pcall(function()
  157.     return makeRequest(test.url, false)
  158.   end)
  159.  
  160.   local expectException = (test.category == "client_error" or test.category == "server_error")
  161.  
  162.   if expectException then
  163.     -- Expect exception for 4xx/5xx errors
  164.     if success then
  165.       errorPrint("Expected exception, but request succeeded!")
  166.       if result then
  167.         colorPrint(colors.yellow, string.format("      📈 Code: %s, Body: %d bytes", result.code or "nil", result.bodyLength or 0))
  168.       end
  169.     else
  170.       successPrint("Got expected exception")
  171.       successCount = successCount + 1
  172.     end
  173.   else
  174.     -- Expect success for 2xx codes
  175.     if success and result then
  176.       successPrint(string.format("Code %s, Body: %d bytes", result.code, result.bodyLength))
  177.       successCount = successCount + 1
  178.     else
  179.       errorPrint("Unexpected exception")
  180.       colorPrint(colors.red, string.format("      💥 Error: %s", tostring(result)))
  181.     end
  182.   end
  183.  
  184.   os.sleep(0.3) -- Pause between requests
  185. end
  186.  
  187. -- Test 1 result
  188. print()
  189. local test1Success = successCount == totalCount
  190. if test1Success then
  191.   colorPrint(colors.bg_green .. colors.white .. colors.bold, string.format(" ✅ TEST 1 PASSED: %d/%d successful ", successCount, totalCount))
  192. else
  193.   colorPrint(colors.bg_red .. colors.white .. colors.bold, string.format(" ❌ TEST 1 FAILED: %d/%d successful ", successCount, totalCount))
  194. end
  195.  
  196. headerPrint("TEST 2: New behavior (allowErrorBody = true)")
  197. infoPrint("HTTP errors should return response body without exceptions")
  198. infoPrint("All codes should work and return data")
  199.  
  200. local successCount2 = 0
  201. local totalCount2 = 0
  202.  
  203. for i, test in ipairs(testUrls) do
  204.   totalCount2 = totalCount2 + 1
  205.  
  206.   -- Colored output for different categories
  207.   local categoryColor = colors.white
  208.   if test.category == "success" then categoryColor = colors.green
  209.   elseif test.category == "redirect" then categoryColor = colors.yellow
  210.   elseif test.category == "client_error" then categoryColor = colors.red
  211.   elseif test.category == "server_error" then categoryColor = colors.magenta
  212.   end
  213.  
  214.   colorPrint(colors.cyan, string.format("   🔍 Test %d: %s", i, test.url))
  215.   colorPrint(categoryColor, string.format("      📊 %d %s [%s]", test.code, test.desc, test.category))
  216.  
  217.   local success, result = pcall(function()
  218.     return makeRequest(test.url, true)
  219.   end)
  220.  
  221.   if success and result then
  222.     successPrint(string.format("Code %s, Message: %s", result.code, result.message or "nil"))
  223.     colorPrint(colors.blue, string.format("      📦 Category: %s, Body: %d bytes", test.category, result.bodyLength))
  224.  
  225.     -- Check code matching
  226.     if result.code == test.code then
  227.       colorPrint(colors.green, "      ✅ Response code matches expected")
  228.       successCount2 = successCount2 + 1
  229.     else
  230.       errorPrint(string.format("Code mismatch: expected %d, got %s", test.code, result.code))
  231.     end
  232.  
  233.     -- Additional checks for different categories
  234.     if test.category == "client_error" or test.category == "server_error" then
  235.       if result.bodyLength > 0 then
  236.         colorPrint(colors.green, "      🎉 Error body received (new behavior works!)")
  237.       else
  238.         warningPrint("Error body is empty")
  239.       end
  240.     end
  241.   else
  242.     errorPrint("Unexpected exception")
  243.     colorPrint(colors.red, string.format("      💥 Error: %s", tostring(result)))
  244.   end
  245.  
  246.   os.sleep(0.3) -- Pause between requests
  247. end
  248.  
  249. -- Test 2 result
  250. print()
  251. local test2Success = successCount2 == totalCount2
  252. if test2Success then
  253.   colorPrint(colors.bg_green .. colors.white .. colors.bold, string.format(" ✅ TEST 2 PASSED: %d/%d successful ", successCount2, totalCount2))
  254. else
  255.   colorPrint(colors.bg_red .. colors.white .. colors.bold, string.format(" ❌ TEST 2 FAILED: %d/%d successful ", successCount2, totalCount2))
  256. end
  257.  
  258. headerPrint("TEST 3: Error body reading demonstration")
  259.  
  260. local errorUrl = "https://httpbin.org/status/418" -- I'm a teapot
  261. infoPrint(string.format("Special request to %s", errorUrl))
  262. colorPrint(colors.yellow, "   🫖 Testing famous 418 'I'm a teapot' code")
  263.  
  264. local success, result = pcall(function()
  265.   return makeRequest(errorUrl, true)
  266. end)
  267.  
  268. if success and result then
  269.   successPrint(string.format("Code: %s (%s)", result.code, result.message or ""))
  270.   colorPrint(colors.blue, string.format("   📏 Body size: %d bytes", result.bodyLength))
  271.  
  272.   if result.bodyLength > 0 then
  273.     colorPrint(colors.green, "   🎉 Error body successfully received!")
  274.     -- Show first 100 characters of response body
  275.     local preview = result.body:sub(1, 100)
  276.     if #result.body > 100 then
  277.       preview = preview .. "..."
  278.     end
  279.     colorPrint(colors.cyan, string.format("   📄 Preview: %s", preview))
  280.   else
  281.     warningPrint("Response body is empty")
  282.   end
  283. else
  284.   errorPrint("Unexpected exception")
  285.   colorPrint(colors.red, string.format("      💥 Error: %s", tostring(result)))
  286. end
  287.  
  288. -- FINAL RESULTS
  289. print()
  290. print()
  291. colorPrint(colors.bg_blue .. colors.white .. colors.bold, "                                                    ")
  292. colorPrint(colors.bg_blue .. colors.white .. colors.bold, "                FINAL RESULTS                      ")
  293. colorPrint(colors.bg_blue .. colors.white .. colors.bold, "                                                    ")
  294. print()
  295.  
  296. -- Statistics
  297. colorPrint(colors.cyan .. colors.bold, "📊 TEST STATISTICS:")
  298. colorPrint(colors.blue, string.format("   🔸 Test 1 (allowErrorBody=false): %d/%d successful", successCount, totalCount))
  299. colorPrint(colors.blue, string.format("   🔸 Test 2 (allowErrorBody=true):  %d/%d successful", successCount2, totalCount2))
  300. colorPrint(colors.magenta .. colors.bold, string.format("   📈 Overall result: %d/%d tests passed", successCount + successCount2, totalCount + totalCount2))
  301. print()
  302.  
  303. -- Overall result
  304. local overallSuccess = (successCount == totalCount) and (successCount2 == totalCount2)
  305. if overallSuccess then
  306.   colorPrint(colors.bg_green .. colors.white .. colors.bold, "                                                    ")
  307.   colorPrint(colors.bg_green .. colors.white .. colors.bold, "           🎉 ALL TESTS PASSED SUCCESSFULLY!       ")
  308.   colorPrint(colors.bg_green .. colors.white .. colors.bold, "                                                    ")
  309.   print()
  310.   successPrint("Legacy behavior: HTTP errors throw exceptions")
  311.   successPrint("New behavior: HTTP errors return response body")
  312.   successPrint("Backward compatibility: fully preserved")
  313.   successPrint("Support for all HTTP codes: 2xx, 4xx, 5xx")
  314. else
  315.   colorPrint(colors.bg_red .. colors.white .. colors.bold, "                                                    ")
  316.   colorPrint(colors.bg_red .. colors.white .. colors.bold, "            ❌ SOME TESTS FAILED                    ")
  317.   colorPrint(colors.bg_red .. colors.white .. colors.bold, "                                                    ")
  318.   print()
  319.   errorPrint("Check output above for details")
  320. end
  321.  
  322. print()
  323. colorPrint(colors.yellow .. colors.bold, "📋 TESTED HTTP CODES:")
  324. colorPrint(colors.green, "   🟢 2xx (Success): 200, 201, 202")
  325. colorPrint(colors.red, "   🔴 4xx (Client Error): 400, 401, 403, 404, 418")
  326. colorPrint(colors.magenta, "   🟣 5xx (Server Error): 500, 502, 503")
  327.  
  328. print()
  329. colorPrint(colors.cyan .. colors.bold, "🚀 HTTP Error Body Fix v2.0 - Testing completed!")
  330. print()
  331.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement