Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- HTTP Error Body Test for OpenComputers
- -- Tests the new allowErrorBody parameter in internet.request()
- local internet = require("internet")
- local component = require("component")
- -- ANSI colors for beautiful output
- local colors = {
- reset = "\27[0m",
- bold = "\27[1m",
- red = "\27[31m",
- green = "\27[32m",
- yellow = "\27[33m",
- blue = "\27[34m",
- magenta = "\27[35m",
- cyan = "\27[36m",
- white = "\27[37m",
- bg_red = "\27[41m",
- bg_green = "\27[42m",
- bg_blue = "\27[44m"
- }
- -- Functions for colored output
- local function colorPrint(color, text)
- print(color .. text .. colors.reset)
- end
- local function successPrint(text)
- colorPrint(colors.green .. colors.bold, "✅ " .. text)
- end
- local function errorPrint(text)
- colorPrint(colors.red .. colors.bold, "❌ " .. text)
- end
- local function warningPrint(text)
- colorPrint(colors.yellow .. colors.bold, "⚠️ " .. text)
- end
- local function infoPrint(text)
- colorPrint(colors.cyan, "ℹ️ " .. text)
- end
- local function headerPrint(text)
- print()
- colorPrint(colors.blue .. colors.bold, "═══ " .. text .. " ═══")
- print()
- end
- -- Check for internet card availability
- if not component.isAvailable("internet") then
- errorPrint("Internet card not found!")
- return
- end
- -- Beautiful header
- print()
- colorPrint(colors.bg_blue .. colors.white .. colors.bold, " ")
- colorPrint(colors.bg_blue .. colors.white .. colors.bold, " HTTP ERROR BODY TEST v2.0 ")
- colorPrint(colors.bg_blue .. colors.white .. colors.bold, " Testing allowErrorBody parameter ")
- colorPrint(colors.bg_blue .. colors.white .. colors.bold, " ")
- print()
- infoPrint("Testing new allowErrorBody parameter in internet.request()")
- infoPrint("Verifying backward compatibility and new functionality")
- print()
- -- Test URLs with different HTTP codes
- local testUrls = {
- -- 2xx Success
- {url = "https://httpbin.org/status/200", code = 200, desc = "OK", category = "success"},
- {url = "https://httpbin.org/status/201", code = 201, desc = "Created", category = "success"},
- {url = "https://httpbin.org/status/202", code = 202, desc = "Accepted", category = "success"},
- -- 4xx Client Error (main ones for testing)
- {url = "https://httpbin.org/status/400", code = 400, desc = "Bad Request", category = "client_error"},
- {url = "https://httpbin.org/status/401", code = 401, desc = "Unauthorized", category = "client_error"},
- {url = "https://httpbin.org/status/403", code = 403, desc = "Forbidden", category = "client_error"},
- {url = "https://httpbin.org/status/404", code = 404, desc = "Not Found", category = "client_error"},
- {url = "https://httpbin.org/status/418", code = 418, desc = "I'm a teapot", category = "client_error"},
- -- 5xx Server Error
- {url = "https://httpbin.org/status/500", code = 500, desc = "Internal Server Error", category = "server_error"},
- {url = "https://httpbin.org/status/502", code = 502, desc = "Bad Gateway", category = "server_error"},
- {url = "https://httpbin.org/status/503", code = 503, desc = "Service Unavailable", category = "server_error"}
- }
- local function makeRequest(url, allowErrorBody)
- -- Use direct component call
- local inet = component.internet
- local request = inet.request(url, nil, nil, nil, allowErrorBody)
- if not request then
- return nil, "request failed"
- end
- -- Wait for response
- local timeout = 0
- while not request.finishConnect() and timeout < 10 do
- os.sleep(0.1)
- timeout = timeout + 0.1
- end
- if timeout >= 10 then
- request:close()
- return nil, "timeout"
- end
- -- Read response
- local response = ""
- while true do
- local chunk = request.read()
- if not chunk then
- break
- elseif #chunk > 0 then
- response = response .. chunk
- else
- os.sleep(0.05)
- end
- end
- -- Get response code
- local code, message = request.response()
- request:close()
- return {
- code = code,
- message = message,
- body = response,
- bodyLength = #response
- }
- end
- -- Test 1: Legacy behavior (allowErrorBody = false)
- headerPrint("TEST 1: Legacy behavior (allowErrorBody = false)")
- infoPrint("HTTP errors should throw exceptions")
- infoPrint("2xx codes should work normally")
- local successCount = 0
- local totalCount = 0
- for i, test in ipairs(testUrls) do
- totalCount = totalCount + 1
- -- Colored output for different categories
- local categoryColor = colors.white
- if test.category == "success" then categoryColor = colors.green
- elseif test.category == "redirect" then categoryColor = colors.yellow
- elseif test.category == "client_error" then categoryColor = colors.red
- elseif test.category == "server_error" then categoryColor = colors.magenta
- end
- colorPrint(colors.cyan, string.format(" 🔍 Test %d: %s", i, test.url))
- colorPrint(categoryColor, string.format(" 📊 %d %s [%s]", test.code, test.desc, test.category))
- local success, result = pcall(function()
- return makeRequest(test.url, false)
- end)
- local expectException = (test.category == "client_error" or test.category == "server_error")
- if expectException then
- -- Expect exception for 4xx/5xx errors
- if success then
- errorPrint("Expected exception, but request succeeded!")
- if result then
- colorPrint(colors.yellow, string.format(" 📈 Code: %s, Body: %d bytes", result.code or "nil", result.bodyLength or 0))
- end
- else
- successPrint("Got expected exception")
- successCount = successCount + 1
- end
- else
- -- Expect success for 2xx codes
- if success and result then
- successPrint(string.format("Code %s, Body: %d bytes", result.code, result.bodyLength))
- successCount = successCount + 1
- else
- errorPrint("Unexpected exception")
- colorPrint(colors.red, string.format(" 💥 Error: %s", tostring(result)))
- end
- end
- os.sleep(0.3) -- Pause between requests
- end
- -- Test 1 result
- print()
- local test1Success = successCount == totalCount
- if test1Success then
- colorPrint(colors.bg_green .. colors.white .. colors.bold, string.format(" ✅ TEST 1 PASSED: %d/%d successful ", successCount, totalCount))
- else
- colorPrint(colors.bg_red .. colors.white .. colors.bold, string.format(" ❌ TEST 1 FAILED: %d/%d successful ", successCount, totalCount))
- end
- headerPrint("TEST 2: New behavior (allowErrorBody = true)")
- infoPrint("HTTP errors should return response body without exceptions")
- infoPrint("All codes should work and return data")
- local successCount2 = 0
- local totalCount2 = 0
- for i, test in ipairs(testUrls) do
- totalCount2 = totalCount2 + 1
- -- Colored output for different categories
- local categoryColor = colors.white
- if test.category == "success" then categoryColor = colors.green
- elseif test.category == "redirect" then categoryColor = colors.yellow
- elseif test.category == "client_error" then categoryColor = colors.red
- elseif test.category == "server_error" then categoryColor = colors.magenta
- end
- colorPrint(colors.cyan, string.format(" 🔍 Test %d: %s", i, test.url))
- colorPrint(categoryColor, string.format(" 📊 %d %s [%s]", test.code, test.desc, test.category))
- local success, result = pcall(function()
- return makeRequest(test.url, true)
- end)
- if success and result then
- successPrint(string.format("Code %s, Message: %s", result.code, result.message or "nil"))
- colorPrint(colors.blue, string.format(" 📦 Category: %s, Body: %d bytes", test.category, result.bodyLength))
- -- Check code matching
- if result.code == test.code then
- colorPrint(colors.green, " ✅ Response code matches expected")
- successCount2 = successCount2 + 1
- else
- errorPrint(string.format("Code mismatch: expected %d, got %s", test.code, result.code))
- end
- -- Additional checks for different categories
- if test.category == "client_error" or test.category == "server_error" then
- if result.bodyLength > 0 then
- colorPrint(colors.green, " 🎉 Error body received (new behavior works!)")
- else
- warningPrint("Error body is empty")
- end
- end
- else
- errorPrint("Unexpected exception")
- colorPrint(colors.red, string.format(" 💥 Error: %s", tostring(result)))
- end
- os.sleep(0.3) -- Pause between requests
- end
- -- Test 2 result
- print()
- local test2Success = successCount2 == totalCount2
- if test2Success then
- colorPrint(colors.bg_green .. colors.white .. colors.bold, string.format(" ✅ TEST 2 PASSED: %d/%d successful ", successCount2, totalCount2))
- else
- colorPrint(colors.bg_red .. colors.white .. colors.bold, string.format(" ❌ TEST 2 FAILED: %d/%d successful ", successCount2, totalCount2))
- end
- headerPrint("TEST 3: Error body reading demonstration")
- local errorUrl = "https://httpbin.org/status/418" -- I'm a teapot
- infoPrint(string.format("Special request to %s", errorUrl))
- colorPrint(colors.yellow, " 🫖 Testing famous 418 'I'm a teapot' code")
- local success, result = pcall(function()
- return makeRequest(errorUrl, true)
- end)
- if success and result then
- successPrint(string.format("Code: %s (%s)", result.code, result.message or ""))
- colorPrint(colors.blue, string.format(" 📏 Body size: %d bytes", result.bodyLength))
- if result.bodyLength > 0 then
- colorPrint(colors.green, " 🎉 Error body successfully received!")
- -- Show first 100 characters of response body
- local preview = result.body:sub(1, 100)
- if #result.body > 100 then
- preview = preview .. "..."
- end
- colorPrint(colors.cyan, string.format(" 📄 Preview: %s", preview))
- else
- warningPrint("Response body is empty")
- end
- else
- errorPrint("Unexpected exception")
- colorPrint(colors.red, string.format(" 💥 Error: %s", tostring(result)))
- end
- -- FINAL RESULTS
- print()
- print()
- colorPrint(colors.bg_blue .. colors.white .. colors.bold, " ")
- colorPrint(colors.bg_blue .. colors.white .. colors.bold, " FINAL RESULTS ")
- colorPrint(colors.bg_blue .. colors.white .. colors.bold, " ")
- print()
- -- Statistics
- colorPrint(colors.cyan .. colors.bold, "📊 TEST STATISTICS:")
- colorPrint(colors.blue, string.format(" 🔸 Test 1 (allowErrorBody=false): %d/%d successful", successCount, totalCount))
- colorPrint(colors.blue, string.format(" 🔸 Test 2 (allowErrorBody=true): %d/%d successful", successCount2, totalCount2))
- colorPrint(colors.magenta .. colors.bold, string.format(" 📈 Overall result: %d/%d tests passed", successCount + successCount2, totalCount + totalCount2))
- print()
- -- Overall result
- local overallSuccess = (successCount == totalCount) and (successCount2 == totalCount2)
- if overallSuccess then
- colorPrint(colors.bg_green .. colors.white .. colors.bold, " ")
- colorPrint(colors.bg_green .. colors.white .. colors.bold, " 🎉 ALL TESTS PASSED SUCCESSFULLY! ")
- colorPrint(colors.bg_green .. colors.white .. colors.bold, " ")
- print()
- successPrint("Legacy behavior: HTTP errors throw exceptions")
- successPrint("New behavior: HTTP errors return response body")
- successPrint("Backward compatibility: fully preserved")
- successPrint("Support for all HTTP codes: 2xx, 4xx, 5xx")
- else
- colorPrint(colors.bg_red .. colors.white .. colors.bold, " ")
- colorPrint(colors.bg_red .. colors.white .. colors.bold, " ❌ SOME TESTS FAILED ")
- colorPrint(colors.bg_red .. colors.white .. colors.bold, " ")
- print()
- errorPrint("Check output above for details")
- end
- print()
- colorPrint(colors.yellow .. colors.bold, "📋 TESTED HTTP CODES:")
- colorPrint(colors.green, " 🟢 2xx (Success): 200, 201, 202")
- colorPrint(colors.red, " 🔴 4xx (Client Error): 400, 401, 403, 404, 418")
- colorPrint(colors.magenta, " 🟣 5xx (Server Error): 500, 502, 503")
- print()
- colorPrint(colors.cyan .. colors.bold, "🚀 HTTP Error Body Fix v2.0 - Testing completed!")
- print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement