refactor: Address issues raised by linter

master
Thijs Schreijer 2022-03-18 12:12:39 +01:00 committed by Caleb Maclennan
parent 480c052572
commit 601ad8d59f
No known key found for this signature in database
GPG Key ID: B538286DE04ECFE5
21 changed files with 187 additions and 198 deletions

View File

@ -5,7 +5,7 @@ local ltn12 = require"ltn12"
local token_class = '[^%c%s%(%)%<%>%@%,%;%:%\\%"%/%[%]%?%=%{%}]' local token_class = '[^%c%s%(%)%<%>%@%,%;%:%\\%"%/%[%]%?%=%{%}]'
local function unquote(t, quoted) local function unquote(t, quoted)
local n = string.match(t, "%$(%d+)$") local n = string.match(t, "%$(%d+)$")
if n then n = tonumber(n) end if n then n = tonumber(n) end
if quoted[n] then return quoted[n] if quoted[n] then return quoted[n]
@ -14,19 +14,19 @@ end
local function parse_set_cookie(c, quoted, cookie_table) local function parse_set_cookie(c, quoted, cookie_table)
c = c .. ";$last=last;" c = c .. ";$last=last;"
local _, __, n, v, i = string.find(c, "(" .. token_class .. local _, _, n, v, i = string.find(c, "(" .. token_class ..
"+)%s*=%s*(.-)%s*;%s*()") "+)%s*=%s*(.-)%s*;%s*()")
local cookie = { local cookie = {
name = n, name = n,
value = unquote(v, quoted), value = unquote(v, quoted),
attributes = {} attributes = {}
} }
while 1 do while 1 do
_, __, n, v, i = string.find(c, "(" .. token_class .. _, _, n, v, i = string.find(c, "(" .. token_class ..
"+)%s*=?%s*(.-)%s*;%s*()", i) "+)%s*=?%s*(.-)%s*;%s*()", i)
if not n or n == "$last" then break end if not n or n == "$last" then break end
cookie.attributes[#cookie.attributes+1] = { cookie.attributes[#cookie.attributes+1] = {
name = n, name = n,
value = unquote(v, quoted) value = unquote(v, quoted)
} }
end end
@ -46,8 +46,8 @@ local function split_set_cookie(s, cookie_table)
-- split into individual cookies -- split into individual cookies
i = 1 i = 1
while 1 do while 1 do
local _, __, cookie, next_token local _, _, cookie, next_token
_, __, cookie, i, next_token = string.find(s, "(.-)%s*%,%s*()(" .. _, _, cookie, i, next_token = string.find(s, "(.-)%s*%,%s*()(" ..
token_class .. "+)%s*=", i) token_class .. "+)%s*=", i)
if not next_token then break end if not next_token then break end
parse_set_cookie(cookie, quoted, cookie_table) parse_set_cookie(cookie, quoted, cookie_table)
@ -62,12 +62,12 @@ local function quote(s)
end end
local _empty = {} local _empty = {}
local function build_cookies(cookies) local function build_cookies(cookies)
s = "" s = ""
for i,v in ipairs(cookies or _empty) do for i,v in ipairs(cookies or _empty) do
if v.name then if v.name then
s = s .. v.name s = s .. v.name
if v.value and v.value ~= "" then if v.value and v.value ~= "" then
s = s .. '=' .. quote(v.value) s = s .. '=' .. quote(v.value)
end end
end end
@ -83,6 +83,6 @@ local function build_cookies(cookies)
end end
if i < #cookies then s = s .. ", " end if i < #cookies then s = s .. ", " end
end end
return s return s
end end

View File

@ -71,7 +71,7 @@ function stats(size)
local current = socket.gettime() local current = socket.gettime()
if chunk then if chunk then
-- total bytes received -- total bytes received
got = got + string.len(chunk) got = got + string.len(chunk)
-- not enough time for estimate -- not enough time for estimate
if current - last > 1 then if current - last > 1 then
io.stderr:write("\r", gauge(got, current - start, size)) io.stderr:write("\r", gauge(got, current - start, size))

View File

@ -1,7 +1,7 @@
local input = source.chain( local input = source.chain(
source.file(io.open("input.bin", "rb")), source.file(io.open("input.bin", "rb")),
encode("base64")) encode("base64"))
local output = sink.chain( local output = sink.chain(
wrap(76), wrap(76),
sink.file(io.open("output.b64", "w"))) sink.file(io.open("output.b64", "w")))
pump.all(input, output) pump.all(input, output)

View File

@ -7,7 +7,7 @@ local function chainpair(f1, f2)
end end
function filter.chain(...) function filter.chain(...)
local f = select(1, ...) local f = select(1, ...)
for i = 2, select('#', ...) do for i = 2, select('#', ...) do
f = chainpair(f, select(i, ...)) f = chainpair(f, select(i, ...))
end end

View File

@ -1,4 +1,4 @@
local qp = filter.chain(normalize(CRLF), encode("quoted-printable"), local qp = filter.chain(normalize(CRLF), encode("quoted-printable"),
wrap("quoted-printable")) wrap("quoted-printable"))
local input = source.chain(source.file(io.stdin), qp) local input = source.chain(source.file(io.stdin), qp)
local output = sink.file(io.stdout) local output = sink.file(io.stdout)

View File

@ -26,7 +26,7 @@ function parse(body)
data[key] = value data[key] = value
end end
end end
return data, code, message return data, code, message
end end
local host = socket.dns.gethostname() local host = socket.dns.gethostname()

View File

@ -56,7 +56,7 @@ end
function metat.__index:login(user, password) function metat.__index:login(user, password)
self.try(self.tp:command("user", user or _M.USER)) self.try(self.tp:command("user", user or _M.USER))
local code, reply = self.try(self.tp:check{"2..", 331}) local code, _ = self.try(self.tp:check{"2..", 331})
if code == 331 then if code == 331 then
self.try(self.tp:command("pass", password or _M.PASSWORD)) self.try(self.tp:command("pass", password or _M.PASSWORD))
self.try(self.tp:check("2..")) self.try(self.tp:check("2.."))
@ -66,7 +66,7 @@ end
function metat.__index:pasv() function metat.__index:pasv()
self.try(self.tp:command("pasv")) self.try(self.tp:command("pasv"))
local code, reply = self.try(self.tp:check("2..")) local _, reply = self.try(self.tp:check("2.."))
local pattern = "(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)" local pattern = "(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)"
local a, b, c, d, p1, p2 = socket.skip(2, string.find(reply, pattern)) local a, b, c, d, p1, p2 = socket.skip(2, string.find(reply, pattern))
self.try(a and b and c and d and p1 and p2, reply) self.try(a and b and c and d and p1 and p2, reply)
@ -83,9 +83,9 @@ end
function metat.__index:epsv() function metat.__index:epsv()
self.try(self.tp:command("epsv")) self.try(self.tp:command("epsv"))
local code, reply = self.try(self.tp:check("229")) local _, reply = self.try(self.tp:check("229"))
local pattern = "%((.)(.-)%1(.-)%1(.-)%1%)" local pattern = "%((.)(.-)%1(.-)%1(.-)%1%)"
local d, prt, address, port = string.match(reply, pattern) local _, _, _, port = string.match(reply, pattern)
self.try(port, "invalid epsv response") self.try(port, "invalid epsv response")
self.pasvt = { self.pasvt = {
address = self.tp:getpeername(), address = self.tp:getpeername(),
@ -102,7 +102,7 @@ end
function metat.__index:port(address, port) function metat.__index:port(address, port)
self.pasvt = nil self.pasvt = nil
if not address then if not address then
address, port = self.try(self.tp:getsockname()) address = self.try(self.tp:getsockname())
self.server = self.try(socket.bind(address, 0)) self.server = self.try(socket.bind(address, 0))
address, port = self.try(self.server:getsockname()) address, port = self.try(self.server:getsockname())
self.try(self.server:settimeout(_M.TIMEOUT)) self.try(self.server:settimeout(_M.TIMEOUT))
@ -118,7 +118,7 @@ end
function metat.__index:eprt(family, address, port) function metat.__index:eprt(family, address, port)
self.pasvt = nil self.pasvt = nil
if not address then if not address then
address, port = self.try(self.tp:getsockname()) address = self.try(self.tp:getsockname())
self.server = self.try(socket.bind(address, 0)) self.server = self.try(socket.bind(address, 0))
address, port = self.try(self.server:getsockname()) address, port = self.try(self.server:getsockname())
self.try(self.server:settimeout(_M.TIMEOUT)) self.try(self.server:settimeout(_M.TIMEOUT))
@ -142,7 +142,7 @@ function metat.__index:send(sendt)
local command = sendt.command or "stor" local command = sendt.command or "stor"
-- send the transfer command and check the reply -- send the transfer command and check the reply
self.try(self.tp:command(command, argument)) self.try(self.tp:command(command, argument))
local code, reply = self.try(self.tp:check{"2..", "1.."}) local code, _ = self.try(self.tp:check{"2..", "1.."})
-- if there is not a pasvt table, then there is a server -- if there is not a pasvt table, then there is a server
-- and we already sent a PORT command -- and we already sent a PORT command
if not self.pasvt then self:portconnect() end if not self.pasvt then self:portconnect() end

View File

@ -41,9 +41,6 @@ local SCHEMES = {
https.tcp, 'LuaSocket: Function tcp() not available from LuaSec') https.tcp, 'LuaSocket: Function tcp() not available from LuaSec')
return tcp(t) end }} return tcp(t) end }}
-- default scheme and port for document retrieval
local SCHEME = 'http'
local PORT = SCHEMES[SCHEME].port
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
-- Reads MIME headers from a connection, unfolding where needed -- Reads MIME headers from a connection, unfolding where needed
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
@ -92,7 +89,7 @@ socket.sourcet["http-chunked"] = function(sock, headers)
-- was it the last chunk? -- was it the last chunk?
if size > 0 then if size > 0 then
-- if not, get chunk and skip terminating CRLF -- if not, get chunk and skip terminating CRLF
local chunk, err, part = sock:receive(size) local chunk, err, _ = sock:receive(size)
if chunk then sock:receive() end if chunk then sock:receive() end
return chunk, err return chunk, err
else else
@ -166,8 +163,8 @@ function metat.__index:receivestatusline()
if status ~= "HTTP/" then if status ~= "HTTP/" then
if ec == "timeout" then if ec == "timeout" then
return 408 return 408
end end
return nil, status return nil, status
end end
-- otherwise proceed reading a status line -- otherwise proceed reading a status line
status = self.try(self.c:receive("*l", status)) status = self.try(self.c:receive("*l", status))
@ -366,7 +363,7 @@ end
local headers local headers
-- ignore any 100-continue messages -- ignore any 100-continue messages
while code == 100 do while code == 100 do
headers = h:receiveheaders() h:receiveheaders()
code, status = h:receivestatusline() code, status = h:receivestatusline()
end end
headers = h:receiveheaders() headers = h:receiveheaders()

View File

@ -13,7 +13,7 @@ local unpack = unpack or table.unpack
local base = _G local base = _G
local _M = {} local _M = {}
if module then -- heuristic for exporting a global package table if module then -- heuristic for exporting a global package table
ltn12 = _M ltn12 = _M -- luacheck: ignore
end end
local filter,source,sink,pump = {},{},{},{} local filter,source,sink,pump = {},{},{},{}
@ -23,7 +23,6 @@ _M.sink = sink
_M.pump = pump _M.pump = pump
local unpack = unpack or table.unpack local unpack = unpack or table.unpack
local select = base.select
-- 2048 seems to be better in windows... -- 2048 seems to be better in windows...
_M.BLOCKSIZE = 2048 _M.BLOCKSIZE = 2048

View File

@ -1,8 +1,8 @@
local _M = {} local _M = {}
if module then if module then
mbox = _M mbox = _M -- luacheck: ignore
end end
function _M.split_message(message_s) function _M.split_message(message_s)
local message = {} local message = {}
@ -29,7 +29,7 @@ end
function _M.parse_header(header_s) function _M.parse_header(header_s)
header_s = string.gsub(header_s, "\n[ ]+", " ") header_s = string.gsub(header_s, "\n[ ]+", " ")
header_s = string.gsub(header_s, "\n+", "") header_s = string.gsub(header_s, "\n+", "")
local _, __, name, value = string.find(header_s, "([^%s:]-):%s*(.*)") local _, _, name, value = string.find(header_s, "([^%s:]-):%s*(.*)")
return name, value return name, value
end end
@ -49,9 +49,9 @@ function _M.parse_headers(headers_s)
end end
function _M.parse_from(from) function _M.parse_from(from)
local _, __, name, address = string.find(from, "^%s*(.-)%s*%<(.-)%>") local _, _, name, address = string.find(from, "^%s*(.-)%s*%<(.-)%>")
if not address then if not address then
_, __, address = string.find(from, "%s*(.+)%s*") _, _, address = string.find(from, "%s*(.+)%s*")
end end
name = name or "" name = name or ""
address = address or "" address = address or ""
@ -63,7 +63,8 @@ end
function _M.split_mbox(mbox_s) function _M.split_mbox(mbox_s)
local mbox = {} local mbox = {}
mbox_s = string.gsub(mbox_s, "\r\n", "\n") .."\n\nFrom \n" mbox_s = string.gsub(mbox_s, "\r\n", "\n") .."\n\nFrom \n"
local nj, i, j = 1, 1, 1 local nj, i
local j = 1
while 1 do while 1 do
i, nj = string.find(mbox_s, "\n\nFrom .-\n", j) i, nj = string.find(mbox_s, "\n\nFrom .-\n", j)
if not i then break end if not i then break end

View File

@ -10,7 +10,6 @@
local base = _G local base = _G
local ltn12 = require("ltn12") local ltn12 = require("ltn12")
local mime = require("mime.core") local mime = require("mime.core")
local string = require("string")
local _M = mime local _M = mime
-- encode, decode and wrap algorithm tables -- encode, decode and wrap algorithm tables
@ -18,7 +17,7 @@ local encodet, decodet, wrapt = {},{},{}
_M.encodet = encodet _M.encodet = encodet
_M.decodet = decodet _M.decodet = decodet
_M.wrapt = wrapt _M.wrapt = wrapt
-- creates a function that chooses a filter by name from a given table -- creates a function that chooses a filter by name from a given table
local function choose(table) local function choose(table)
@ -27,7 +26,7 @@ local function choose(table)
name, opt1, opt2 = "default", name, opt1 name, opt1, opt2 = "default", name, opt1
end end
local f = table[name or "nil"] local f = table[name or "nil"]
if not f then if not f then
base.error("unknown key (" .. base.tostring(name) .. ")", 3) base.error("unknown key (" .. base.tostring(name) .. ")", 3)
else return f(opt1, opt2) end else return f(opt1, opt2) end
end end
@ -52,13 +51,6 @@ decodet['quoted-printable'] = function()
return ltn12.filter.cycle(_M.unqp, "") return ltn12.filter.cycle(_M.unqp, "")
end end
local function format(chunk)
if chunk then
if chunk == "" then return "''"
else return string.len(chunk) end
else return "nil" end
end
-- define the line-wrap filters -- define the line-wrap filters
wrapt['text'] = function(length) wrapt['text'] = function(length)
length = length or 76 length = length or 76

View File

@ -179,9 +179,9 @@ function _M.parse(url, default)
function(u) parsed.userinfo = u; return "" end) function(u) parsed.userinfo = u; return "" end)
authority = string.gsub(authority, ":([^:%]]*)$", authority = string.gsub(authority, ":([^:%]]*)$",
function(p) parsed.port = p; return "" end) function(p) parsed.port = p; return "" end)
if authority ~= "" then if authority ~= "" then
-- IPv6? -- IPv6?
parsed.host = string.match(authority, "^%[(.+)%]$") or authority parsed.host = string.match(authority, "^%[(.+)%]$") or authority
end end
local userinfo = parsed.userinfo local userinfo = parsed.userinfo
if not userinfo then return parsed end if not userinfo then return parsed end
@ -264,7 +264,7 @@ function _M.absolute(base_url, relative_url)
relative_parsed.query = base_parsed.query relative_parsed.query = base_parsed.query
end end
end end
else else
relative_parsed.path = absolute_path(base_parsed.path or "", relative_parsed.path = absolute_path(base_parsed.path or "",
relative_parsed.path) relative_parsed.path)
end end

View File

@ -38,7 +38,7 @@ local function named(f, name)
end end
-------------------------------- --------------------------------
local function split(size) local function split(size)
local buffer = "" local buffer = ""
local last_out = "" local last_out = ""
local last_in = "" local last_in = ""
@ -50,12 +50,12 @@ local function split(size)
return last_out return last_out
end end
return function(chunk, done) return function(chunk, done)
if done then if done then
return not last_in and not last_out return not last_in and not last_out
end end
-- check if argument is consistent with state -- check if argument is consistent with state
if not chunk then if not chunk then
if last_in and last_in ~= "" and last_out ~= "" then if last_in and last_in ~= "" and last_out ~= "" then
error("nil chunk following data chunk", 2) error("nil chunk following data chunk", 2)
end end
if not last_out then error("extra nil chunk", 2) end if not last_out then error("extra nil chunk", 2) end
@ -67,8 +67,8 @@ local function split(size)
return output(chunk) return output(chunk)
else else
if not last_in then error("data chunk following nil chunk", 2) end if not last_in then error("data chunk following nil chunk", 2) end
if last_in ~= "" and last_out ~= "" then if last_in ~= "" and last_out ~= "" then
error("data chunk following data chunk", 2) error("data chunk following data chunk", 2)
end end
buffer = chunk buffer = chunk
return output(chunk) return output(chunk)
@ -85,7 +85,7 @@ local function format(chunk)
end end
-------------------------------- --------------------------------
local function merge(size) local function merge(size)
local buffer = "" local buffer = ""
local last_out = "" local last_out = ""
local last_in = "" local last_in = ""
@ -102,12 +102,12 @@ local function merge(size)
return last_out return last_out
end end
return function(chunk, done) return function(chunk, done)
if done then if done then
return not last_in and not last_out return not last_in and not last_out
end end
-- check if argument is consistent with state -- check if argument is consistent with state
if not chunk then if not chunk then
if last_in and last_in ~= "" and last_out ~= "" then if last_in and last_in ~= "" and last_out ~= "" then
error("nil chunk following data chunk", 2) error("nil chunk following data chunk", 2)
end end
if not last_out then error("extra nil chunk", 2) end if not last_out then error("extra nil chunk", 2) end
@ -119,8 +119,8 @@ local function merge(size)
return output(chunk) return output(chunk)
else else
if not last_in then error("data chunk following nil chunk", 2) end if not last_in then error("data chunk following nil chunk", 2) end
if last_in ~= "" and last_out ~= "" then if last_in ~= "" and last_out ~= "" then
error("data chunk following data chunk", 2) error("data chunk following data chunk", 2)
end end
buffer = buffer .. chunk buffer = buffer .. chunk
return output(chunk) return output(chunk)

View File

@ -15,27 +15,27 @@ local eb64test = "b64test.bin2"
local db64test = "b64test.bin3" local db64test = "b64test.bin3"
-- from Machado de Assis, "A Mão e a Rosa" -- from Machado de Assis, "A M<EFBFBD>o e a Rosa"
local mao = [[ local mao = [[
Cursavam estes dois moços a academia de S. Paulo, estando Cursavam estes dois mo<EFBFBD>os a academia de S. Paulo, estando
Luís Alves no quarto ano e Estêvão no terceiro. Lu<EFBFBD>s Alves no quarto ano e Est<EFBFBD>v<EFBFBD>o no terceiro.
Conheceram-se na academia, e ficaram amigos íntimos, tanto Conheceram-se na academia, e ficaram amigos <EFBFBD>ntimos, tanto
quanto podiam sê-lo dois espíritos diferentes, ou talvez por quanto podiam s<EFBFBD>-lo dois esp<EFBFBD>ritos diferentes, ou talvez por
isso mesmo que o eram. Estêvão, dotado de extrema isso mesmo que o eram. Est<EFBFBD>v<EFBFBD>o, dotado de extrema
sensibilidade, e não menor fraqueza de ânimo, afetuoso e sensibilidade, e n<EFBFBD>o menor fraqueza de <EFBFBD>nimo, afetuoso e
bom, não daquela bondade varonil, que é apanágio de uma alma bom, n<EFBFBD>o daquela bondade varonil, que <EFBFBD> apan<EFBFBD>gio de uma alma
forte, mas dessa outra bondade mole e de cera, que vai à forte, mas dessa outra bondade mole e de cera, que vai <EFBFBD>
mercê de todas as circunstâncias, tinha, além de tudo isso, merc<EFBFBD> de todas as circunst<EFBFBD>ncias, tinha, al<EFBFBD>m de tudo isso,
o infortúnio de trazer ainda sobre o nariz os óculos o infort<EFBFBD>nio de trazer ainda sobre o nariz os <EFBFBD>culos
cor-de-rosa de suas virginais ilusões. Luís Alves via bem cor-de-rosa de suas virginais ilus<EFBFBD>es. Lu<EFBFBD>s Alves via bem
com os olhos da cara. Não era mau rapaz, mas tinha o seu com os olhos da cara. N<EFBFBD>o era mau rapaz, mas tinha o seu
grão de egoísmo, e se não era incapaz de afeições, sabia gr<EFBFBD>o de ego<EFBFBD>smo, e se n<EFBFBD>o era incapaz de afei<EFBFBD><EFBFBD>es, sabia
regê-las, moderá-las, e sobretudo guiá-las ao seu próprio reg<EFBFBD>-las, moder<EFBFBD>-las, e sobretudo gui<EFBFBD>-las ao seu pr<EFBFBD>prio
interesse. Entre estes dois homens travara-se amizade interesse. Entre estes dois homens travara-se amizade
íntima, nascida para um na simpatia, para outro no costume. <EFBFBD>ntima, nascida para um na simpatia, para outro no costume.
Eram eles os naturais confidentes um do outro, com a Eram eles os naturais confidentes um do outro, com a
diferença que Luís Alves dava menos do que recebia, e, ainda diferen<EFBFBD>a que Lu<EFBFBD>s Alves dava menos do que recebia, e, ainda
assim, nem tudo o que dava exprimia grande confiança. assim, nem tudo o que dava exprimia grande confian<EFBFBD>a.
]] ]]
local function random(handle, io_err) local function random(handle, io_err)
@ -44,8 +44,8 @@ local function random(handle, io_err)
if not handle then error("source is empty!", 2) end if not handle then error("source is empty!", 2) end
local len = math.random(0, 1024) local len = math.random(0, 1024)
local chunk = handle:read(len) local chunk = handle:read(len)
if not chunk then if not chunk then
handle:close() handle:close()
handle = nil handle = nil
end end
return chunk return chunk
@ -62,7 +62,7 @@ local what = nil
local function transform(input, output, filter) local function transform(input, output, filter)
local source = random(io.open(input, "rb")) local source = random(io.open(input, "rb"))
local sink = ltn12.sink.file(io.open(output, "wb")) local sink = ltn12.sink.file(io.open(output, "wb"))
if what then if what then
sink = ltn12.sink.chain(filter, sink) sink = ltn12.sink.chain(filter, sink)
else else
source = ltn12.source.chain(source, filter) source = ltn12.source.chain(source, filter)
@ -147,7 +147,7 @@ local function create_qptest()
f:write(' ',string.char(32)) f:write(' ',string.char(32))
end end
f:write("\r\n") f:write("\r\n")
f:close() f:close()
end end
@ -157,7 +157,7 @@ local function cleanup_qptest()
os.remove(dqptest) os.remove(dqptest)
end end
-- create test file -- create test file
local function create_b64test() local function create_b64test()
local f = assert(io.open(b64test, "wb")) local f = assert(io.open(b64test, "wb"))
local t = {} local t = {}

View File

@ -27,8 +27,8 @@ local total = function()
end end
local similar = function(s1, s2) local similar = function(s1, s2)
return return
string.lower(string.gsub(s1, "%s", "")) == string.lower(string.gsub(s1, "%s", "")) ==
string.lower(string.gsub(s2, "%s", "")) string.lower(string.gsub(s2, "%s", ""))
end end
@ -40,9 +40,9 @@ end
local readfile = function(name) local readfile = function(name)
local f = io.open(name, "r") local f = io.open(name, "r")
if not f then if not f then
fail("unable to open file!") fail("unable to open file!")
return nil return nil
end end
local s = f:read("*a") local s = f:read("*a")
f:close() f:close()
@ -52,7 +52,7 @@ end
local empty = function() local empty = function()
for i,v in ipairs(files) do for i,v in ipairs(files) do
local f = io.open(v, "w") local f = io.open(v, "w")
if not f then if not f then
fail("unable to open file!") fail("unable to open file!")
end end
f:close() f:close()
@ -116,8 +116,8 @@ local wait = function(sentinel, n)
while 1 do while 1 do
local mbox = parse(get()) local mbox = parse(get())
if n == #mbox then break end if n == #mbox then break end
if socket.time() - sentinel.time > 50 then if socket.time() - sentinel.time > 50 then
to = 1 to = 1
break break
end end
socket.sleep(1) socket.sleep(1)
@ -132,7 +132,7 @@ local stuffed_body = [[
This message body needs to be This message body needs to be
stuffed because it has a dot stuffed because it has a dot
. .
by itself on a line. by itself on a line.
Otherwise the mailer would Otherwise the mailer would
think that the dot think that the dot
. .
@ -219,7 +219,7 @@ else print("ok") end
io.write("testing invalid from: ") io.write("testing invalid from: ")
local ret, err = socket.smtp.mail{ local ret, err = socket.smtp.mail{
from = ' " " (( _ * ', from = ' " " (( _ * ',
rcpt = rcpt, rcpt = rcpt,
} }
if ret or not err then fail("wrong error message") if ret or not err then fail("wrong error message")
@ -227,7 +227,7 @@ else print(err) end
io.write("testing no rcpt: ") io.write("testing no rcpt: ")
local ret, err = socket.smtp.mail{ local ret, err = socket.smtp.mail{
from = from, from = from,
} }
if ret or not err then fail("wrong error message") if ret or not err then fail("wrong error message")
else print(err) end else print(err) end

View File

@ -19,7 +19,7 @@ for i = 1, 10 do
assert(ss == sock) assert(ss == sock)
else else
assert('timeout' == err, 'unexpected error :' .. tostring(err)) assert('timeout' == err, 'unexpected error :' .. tostring(err))
end end
err = sock:getoption("error") -- i get 'connection refused' on WinXP err = sock:getoption("error") -- i get 'connection refused' on WinXP
if err then if err then
print("Passed! Error is '" .. err .. "'.") print("Passed! Error is '" .. err .. "'.")

View File

@ -34,11 +34,11 @@ r, e = smtp.send{
print(r, e) print(r, e)
-- creates a source to send a message with two parts. The first part is -- creates a source to send a message with two parts. The first part is
-- plain text, the second part is a PNG image, encoded as base64. -- plain text, the second part is a PNG image, encoded as base64.
source = smtp.message{ source = smtp.message{
headers = { headers = {
-- Remember that headers are *ignored* by smtp.send. -- Remember that headers are *ignored* by smtp.send.
from = "Sicrano <sicrano@tecgraf.puc-rio.br>", from = "Sicrano <sicrano@tecgraf.puc-rio.br>",
to = "Fulano <fulano@tecgraf.puc-rio.br>", to = "Fulano <fulano@tecgraf.puc-rio.br>",
subject = "Here is a message with attachments" subject = "Here is a message with attachments"
@ -49,18 +49,18 @@ source = smtp.message{
"Preamble might show up even in a MIME enabled client.", "Preamble might show up even in a MIME enabled client.",
-- first part: No headers means plain text, us-ascii. -- first part: No headers means plain text, us-ascii.
-- The mime.eol low-level filter normalizes end-of-line markers. -- The mime.eol low-level filter normalizes end-of-line markers.
[1] = { [1] = {
body = mime.eol(0, [[ body = mime.eol(0, [[
Lines in a message body should always end with CRLF. Lines in a message body should always end with CRLF.
The smtp module will *NOT* perform translation. It will The smtp module will *NOT* perform translation. It will
perform necessary stuffing, though. perform necessary stuffing, though.
]]) ]])
}, },
-- second part: Headers describe content the to be an image, -- second part: Headers describe content the to be an image,
-- sent under the base64 transfer content encoding. -- sent under the base64 transfer content encoding.
-- Notice that nothing happens until the message is sent. Small -- Notice that nothing happens until the message is sent. Small
-- chunks are loaded into memory and translation happens on the fly. -- chunks are loaded into memory and translation happens on the fly.
[2] = { [2] = {
headers = { headers = {
["ConTenT-tYpE"] = 'image/png; name="luasocket.png"', ["ConTenT-tYpE"] = 'image/png; name="luasocket.png"',
["content-disposition"] = 'attachment; filename="luasocket.png"', ["content-disposition"] = 'attachment; filename="luasocket.png"',

View File

@ -7,7 +7,7 @@ function readfile(name)
end end
function similar(s1, s2) function similar(s1, s2)
return string.lower(string.gsub(s1 or "", "%s", "")) == return string.lower(string.gsub(s1 or "", "%s", "")) ==
string.lower(string.gsub(s2 or "", "%s", "")) string.lower(string.gsub(s2 or "", "%s", ""))
end end

View File

@ -60,8 +60,8 @@ end
local check_absolute_url = function(base, relative, absolute) local check_absolute_url = function(base, relative, absolute)
local res = socket.url.absolute(base, relative) local res = socket.url.absolute(base, relative)
if res ~= absolute then if res ~= absolute then
io.write("absolute: In test for base='", base, "', rel='", relative, "' expected '", io.write("absolute: In test for base='", base, "', rel='", relative, "' expected '",
absolute, "' but got '", res, "'\n") absolute, "' but got '", res, "'\n")
os.exit() os.exit()
end end
@ -73,7 +73,7 @@ local check_parse_url = function(gaba)
local parsed = socket.url.parse(url) local parsed = socket.url.parse(url)
for i, v in pairs(gaba) do for i, v in pairs(gaba) do
if v ~= parsed[i] then if v ~= parsed[i] then
io.write("parse: In test for '", url, "' expected ", i, " = '", io.write("parse: In test for '", url, "' expected ", i, " = '",
v, "' but got '", tostring(parsed[i]), "'\n") v, "' but got '", tostring(parsed[i]), "'\n")
for i,v in pairs(parsed) do print(i,v) end for i,v in pairs(parsed) do print(i,v) end
os.exit() os.exit()
@ -81,7 +81,7 @@ local check_parse_url = function(gaba)
end end
for i, v in pairs(parsed) do for i, v in pairs(parsed) do
if v ~= gaba[i] then if v ~= gaba[i] then
io.write("parse: In test for '", url, "' expected ", i, " = '", io.write("parse: In test for '", url, "' expected ", i, " = '",
tostring(gaba[i]), "' but got '", v, "'\n") tostring(gaba[i]), "' but got '", v, "'\n")
for i,v in pairs(parsed) do print(i,v) end for i,v in pairs(parsed) do print(i,v) end
os.exit() os.exit()
@ -92,8 +92,8 @@ end
print("testing URL parsing") print("testing URL parsing")
check_parse_url{ check_parse_url{
url = "scheme://user:pass$%?#wd@host:port/path;params?query#fragment", url = "scheme://user:pass$%?#wd@host:port/path;params?query#fragment",
scheme = "scheme", scheme = "scheme",
authority = "user:pass$%?#wd@host:port", authority = "user:pass$%?#wd@host:port",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "user:pass$%?#wd", userinfo = "user:pass$%?#wd",
@ -106,8 +106,8 @@ check_parse_url{
} }
check_parse_url{ check_parse_url{
url = "scheme://user:pass?#wd@host:port/path;params?query#fragment", url = "scheme://user:pass?#wd@host:port/path;params?query#fragment",
scheme = "scheme", scheme = "scheme",
authority = "user:pass?#wd@host:port", authority = "user:pass?#wd@host:port",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "user:pass?#wd", userinfo = "user:pass?#wd",
@ -120,8 +120,8 @@ check_parse_url{
} }
check_parse_url{ check_parse_url{
url = "scheme://user:pass-wd@host:port/path;params?query#fragment", url = "scheme://user:pass-wd@host:port/path;params?query#fragment",
scheme = "scheme", scheme = "scheme",
authority = "user:pass-wd@host:port", authority = "user:pass-wd@host:port",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "user:pass-wd", userinfo = "user:pass-wd",
@ -134,8 +134,8 @@ check_parse_url{
} }
check_parse_url{ check_parse_url{
url = "scheme://user:pass#wd@host:port/path;params?query#fragment", url = "scheme://user:pass#wd@host:port/path;params?query#fragment",
scheme = "scheme", scheme = "scheme",
authority = "user:pass#wd@host:port", authority = "user:pass#wd@host:port",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "user:pass#wd", userinfo = "user:pass#wd",
@ -148,8 +148,8 @@ check_parse_url{
} }
check_parse_url{ check_parse_url{
url = "scheme://user:pass#wd@host:port/path;params?query", url = "scheme://user:pass#wd@host:port/path;params?query",
scheme = "scheme", scheme = "scheme",
authority = "user:pass#wd@host:port", authority = "user:pass#wd@host:port",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "user:pass#wd", userinfo = "user:pass#wd",
@ -161,8 +161,8 @@ check_parse_url{
} }
check_parse_url{ check_parse_url{
url = "scheme://userinfo@host:port/path;params?query#fragment", url = "scheme://userinfo@host:port/path;params?query#fragment",
scheme = "scheme", scheme = "scheme",
authority = "userinfo@host:port", authority = "userinfo@host:port",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "userinfo", userinfo = "userinfo",
@ -175,8 +175,8 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "scheme://user:password@host:port/path;params?query#fragment", url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme", scheme = "scheme",
authority = "user:password@host:port", authority = "user:password@host:port",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "user:password", userinfo = "user:password",
@ -190,8 +190,8 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "scheme://userinfo@host:port/path;params?query#", url = "scheme://userinfo@host:port/path;params?query#",
scheme = "scheme", scheme = "scheme",
authority = "userinfo@host:port", authority = "userinfo@host:port",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "userinfo", userinfo = "userinfo",
@ -204,8 +204,8 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "scheme://userinfo@host:port/path;params?#fragment", url = "scheme://userinfo@host:port/path;params?#fragment",
scheme = "scheme", scheme = "scheme",
authority = "userinfo@host:port", authority = "userinfo@host:port",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "userinfo", userinfo = "userinfo",
@ -218,8 +218,8 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "scheme://userinfo@host:port/path;params#fragment", url = "scheme://userinfo@host:port/path;params#fragment",
scheme = "scheme", scheme = "scheme",
authority = "userinfo@host:port", authority = "userinfo@host:port",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "userinfo", userinfo = "userinfo",
@ -231,8 +231,8 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "scheme://userinfo@host:port/path;?query#fragment", url = "scheme://userinfo@host:port/path;?query#fragment",
scheme = "scheme", scheme = "scheme",
authority = "userinfo@host:port", authority = "userinfo@host:port",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "userinfo", userinfo = "userinfo",
@ -245,8 +245,8 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "scheme://userinfo@host:port/path?query#fragment", url = "scheme://userinfo@host:port/path?query#fragment",
scheme = "scheme", scheme = "scheme",
authority = "userinfo@host:port", authority = "userinfo@host:port",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "userinfo", userinfo = "userinfo",
@ -258,8 +258,8 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "scheme://userinfo@host:port/;params?query#fragment", url = "scheme://userinfo@host:port/;params?query#fragment",
scheme = "scheme", scheme = "scheme",
authority = "userinfo@host:port", authority = "userinfo@host:port",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "userinfo", userinfo = "userinfo",
@ -272,8 +272,8 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "scheme://userinfo@host:port", url = "scheme://userinfo@host:port",
scheme = "scheme", scheme = "scheme",
authority = "userinfo@host:port", authority = "userinfo@host:port",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "userinfo", userinfo = "userinfo",
@ -282,7 +282,7 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "//userinfo@host:port/path;params?query#fragment", url = "//userinfo@host:port/path;params?query#fragment",
authority = "userinfo@host:port", authority = "userinfo@host:port",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "userinfo", userinfo = "userinfo",
@ -295,7 +295,7 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "//userinfo@host:port/path", url = "//userinfo@host:port/path",
authority = "userinfo@host:port", authority = "userinfo@host:port",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "userinfo", userinfo = "userinfo",
@ -305,7 +305,7 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "//userinfo@host/path", url = "//userinfo@host/path",
authority = "userinfo@host", authority = "userinfo@host",
host = "host", host = "host",
userinfo = "userinfo", userinfo = "userinfo",
user = "userinfo", user = "userinfo",
@ -314,7 +314,7 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "//user:password@host/path", url = "//user:password@host/path",
authority = "user:password@host", authority = "user:password@host",
host = "host", host = "host",
userinfo = "user:password", userinfo = "user:password",
password = "password", password = "password",
@ -324,7 +324,7 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "//user:@host/path", url = "//user:@host/path",
authority = "user:@host", authority = "user:@host",
host = "host", host = "host",
userinfo = "user:", userinfo = "user:",
password = "", password = "",
@ -334,7 +334,7 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "//user@host:port/path", url = "//user@host:port/path",
authority = "user@host:port", authority = "user@host:port",
host = "host", host = "host",
userinfo = "user", userinfo = "user",
user = "user", user = "user",
@ -344,7 +344,7 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "//host:port/path", url = "//host:port/path",
authority = "host:port", authority = "host:port",
port = "port", port = "port",
host = "host", host = "host",
path = "/path", path = "/path",
@ -352,14 +352,14 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "//host/path", url = "//host/path",
authority = "host", authority = "host",
host = "host", host = "host",
path = "/path", path = "/path",
} }
check_parse_url{ check_parse_url{
url = "//host", url = "//host",
authority = "host", authority = "host",
host = "host", host = "host",
} }
@ -433,7 +433,7 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "//userinfo@[::FFFF:129.144.52.38]:port/path;params?query#fragment", url = "//userinfo@[::FFFF:129.144.52.38]:port/path;params?query#fragment",
authority = "userinfo@[::FFFF:129.144.52.38]:port", authority = "userinfo@[::FFFF:129.144.52.38]:port",
host = "::FFFF:129.144.52.38", host = "::FFFF:129.144.52.38",
port = "port", port = "port",
userinfo = "userinfo", userinfo = "userinfo",
@ -447,7 +447,7 @@ check_parse_url{
check_parse_url{ check_parse_url{
url = "scheme://user:password@[::192.9.5.5]:port/path;params?query#fragment", url = "scheme://user:password@[::192.9.5.5]:port/path;params?query#fragment",
scheme = "scheme", scheme = "scheme",
authority = "user:password@[::192.9.5.5]:port", authority = "user:password@[::192.9.5.5]:port",
host = "::192.9.5.5", host = "::192.9.5.5",
port = "port", port = "port",
userinfo = "user:password", userinfo = "user:password",
@ -462,7 +462,7 @@ check_parse_url{
print("testing URL building") print("testing URL building")
check_build_url { check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment", url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme", scheme = "scheme",
host = "host", host = "host",
port = "port", port = "port",
user = "user", user = "user",
@ -499,7 +499,7 @@ check_build_url{
check_build_url { check_build_url {
url = "scheme://user:password@host/path;params?query#fragment", url = "scheme://user:password@host/path;params?query#fragment",
scheme = "scheme", scheme = "scheme",
host = "host", host = "host",
user = "user", user = "user",
password = "password", password = "password",
@ -511,7 +511,7 @@ check_build_url {
check_build_url { check_build_url {
url = "scheme://user@host/path;params?query#fragment", url = "scheme://user@host/path;params?query#fragment",
scheme = "scheme", scheme = "scheme",
host = "host", host = "host",
user = "user", user = "user",
path = "/path", path = "/path",
@ -522,7 +522,7 @@ check_build_url {
check_build_url { check_build_url {
url = "scheme://host/path;params?query#fragment", url = "scheme://host/path;params?query#fragment",
scheme = "scheme", scheme = "scheme",
host = "host", host = "host",
path = "/path", path = "/path",
params = "params", params = "params",
@ -532,7 +532,7 @@ check_build_url {
check_build_url { check_build_url {
url = "scheme://host/path;params#fragment", url = "scheme://host/path;params#fragment",
scheme = "scheme", scheme = "scheme",
host = "host", host = "host",
path = "/path", path = "/path",
params = "params", params = "params",
@ -541,7 +541,7 @@ check_build_url {
check_build_url { check_build_url {
url = "scheme://host/path#fragment", url = "scheme://host/path#fragment",
scheme = "scheme", scheme = "scheme",
host = "host", host = "host",
path = "/path", path = "/path",
fragment = "fragment" fragment = "fragment"
@ -549,7 +549,7 @@ check_build_url {
check_build_url { check_build_url {
url = "scheme://host/path", url = "scheme://host/path",
scheme = "scheme", scheme = "scheme",
host = "host", host = "host",
path = "/path", path = "/path",
} }
@ -567,7 +567,7 @@ check_build_url {
check_build_url { check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment", url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme", scheme = "scheme",
host = "host", host = "host",
port = "port", port = "port",
user = "user", user = "user",
@ -581,7 +581,7 @@ check_build_url {
check_build_url { check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment", url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme", scheme = "scheme",
host = "host", host = "host",
port = "port", port = "port",
user = "user", user = "user",
@ -596,7 +596,7 @@ check_build_url {
check_build_url { check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment", url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme", scheme = "scheme",
host = "host", host = "host",
port = "port", port = "port",
userinfo = "user:password", userinfo = "user:password",
@ -609,7 +609,7 @@ check_build_url {
check_build_url { check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment", url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme", scheme = "scheme",
authority = "user:password@host:port", authority = "user:password@host:port",
path = "/path", path = "/path",
params = "params", params = "params",
@ -683,7 +683,7 @@ check_absolute_url("//a/b/c/d;p?q#f", "d/e/f", "//a/b/c/d/e/f")
check_absolute_url("/a/b/c/d;p?q#f", "d/e/f", "/a/b/c/d/e/f") check_absolute_url("/a/b/c/d;p?q#f", "d/e/f", "/a/b/c/d/e/f")
check_absolute_url("a/b/c/d", "d/e/f", "a/b/c/d/e/f") check_absolute_url("a/b/c/d", "d/e/f", "a/b/c/d/e/f")
check_absolute_url("a/b/c/d/../", "d/e/f", "a/b/c/d/e/f") check_absolute_url("a/b/c/d/../", "d/e/f", "a/b/c/d/e/f")
check_absolute_url("http://velox.telemar.com.br", "/dashboard/index.html", check_absolute_url("http://velox.telemar.com.br", "/dashboard/index.html",
"http://velox.telemar.com.br/dashboard/index.html") "http://velox.telemar.com.br/dashboard/index.html")
check_absolute_url("http://example.com/", "../.badhost.com/", "http://example.com/.badhost.com/") check_absolute_url("http://example.com/", "../.badhost.com/", "http://example.com/.badhost.com/")
check_absolute_url("http://example.com/", "...badhost.com/", "http://example.com/...badhost.com/") check_absolute_url("http://example.com/", "...badhost.com/", "http://example.com/...badhost.com/")
@ -700,11 +700,11 @@ check_absolute_url("http://example.com/a/b/c/d/", "../x/a/../y/z/../../../../q",
print("testing path parsing and composition") print("testing path parsing and composition")
check_parse_path("/eu/tu/ele", { "eu", "tu", "ele"; is_absolute = 1 }) check_parse_path("/eu/tu/ele", { "eu", "tu", "ele"; is_absolute = 1 })
check_parse_path("/eu/", { "eu"; is_absolute = 1, is_directory = 1 }) check_parse_path("/eu/", { "eu"; is_absolute = 1, is_directory = 1 })
check_parse_path("eu/tu/ele/nos/vos/eles/", check_parse_path("eu/tu/ele/nos/vos/eles/",
{ "eu", "tu", "ele", "nos", "vos", "eles"; is_directory = 1}) { "eu", "tu", "ele", "nos", "vos", "eles"; is_directory = 1})
check_parse_path("/", { is_absolute = 1, is_directory = 1}) check_parse_path("/", { is_absolute = 1, is_directory = 1})
check_parse_path("", { }) check_parse_path("", { })
check_parse_path("eu%01/%02tu/e%03l%04e/nos/vos%05/e%12les/", check_parse_path("eu%01/%02tu/e%03l%04e/nos/vos%05/e%12les/",
{ "eu\1", "\2tu", "e\3l\4e", "nos", "vos\5", "e\18les"; is_directory = 1}) { "eu\1", "\2tu", "e\3l\4e", "nos", "vos\5", "e\18les"; is_directory = 1})
check_parse_path("eu/tu", { "eu", "tu" }) check_parse_path("eu/tu", { "eu", "tu" })

View File

@ -54,30 +54,30 @@ function check_timeout(tm, sl, elapsed, err, opp, mode, alldone)
if not err then warn("must be buffered") if not err then warn("must be buffered")
elseif err == "timeout" then pass("proper timeout") elseif err == "timeout" then pass("proper timeout")
else fail("unexpected error '%s'", err) end else fail("unexpected error '%s'", err) end
else else
if err ~= "timeout" then fail("should have timed out") if err ~= "timeout" then fail("should have timed out")
else pass("proper timeout") end else pass("proper timeout") end
end end
else else
if mode == "total" then if mode == "total" then
if elapsed > tm then if elapsed > tm then
if err ~= "timeout" then fail("should have timed out") if err ~= "timeout" then fail("should have timed out")
else pass("proper timeout") end else pass("proper timeout") end
elseif elapsed < tm then elseif elapsed < tm then
if err then fail(err) if err then fail(err)
else pass("ok") end else pass("ok") end
else else
if alldone then if alldone then
if err then fail("unexpected error '%s'", err) if err then fail("unexpected error '%s'", err)
else pass("ok") end else pass("ok") end
else else
if err ~= "timeout" then fail(err) if err ~= "timeout" then fail(err)
else pass("proper timeoutk") end else pass("proper timeoutk") end
end end
end end
else else
if err then fail(err) if err then fail(err)
else pass("ok") end else pass("ok") end
end end
end end
end end
@ -104,7 +104,7 @@ function reconnect()
print("done " .. i) print("done " .. i)
]] ]]
data, err = uconnect(host, port) data, err = uconnect(host, port)
if not data then fail(err) if not data then fail(err)
else pass("connected!") end else pass("connected!") end
end end
@ -116,8 +116,8 @@ else pass("connected!") end
------------------------------------------------------------------------ ------------------------------------------------------------------------
function test_methods(sock, methods) function test_methods(sock, methods)
for _, v in pairs(methods) do for _, v in pairs(methods) do
if type(sock[v]) ~= "function" then if type(sock[v]) ~= "function" then
fail(sock.class .. " method '" .. v .. "' not registered") fail(sock.class .. " method '" .. v .. "' not registered")
end end
end end
pass(sock.class .. " methods are ok") pass(sock.class .. " methods are ok")
@ -132,7 +132,7 @@ function test_mixed(len)
local p3 = "raw " .. string.rep("z", inter) .. "bytes" local p3 = "raw " .. string.rep("z", inter) .. "bytes"
local p4 = "end" .. string.rep("w", inter) .. "bytes" local p4 = "end" .. string.rep("w", inter) .. "bytes"
local bp1, bp2, bp3, bp4 local bp1, bp2, bp3, bp4
remote (string.format("str = data:receive(%d)", remote (string.format("str = data:receive(%d)",
string.len(p1)+string.len(p2)+string.len(p3)+string.len(p4))) string.len(p1)+string.len(p2)+string.len(p3)+string.len(p4)))
sent, err = data:send(p1..p2..p3..p4) sent, err = data:send(p1..p2..p3..p4)
if err then fail(err) end if err then fail(err) end
@ -172,7 +172,7 @@ function test_rawline(len)
reconnect() reconnect()
local str, str10, back, err local str, str10, back, err
str = string.rep(string.char(47), math.mod(len, 10)) str = string.rep(string.char(47), math.mod(len, 10))
str10 = string.rep(string.char(120,21,77,4,5,0,7,36,44,100), str10 = string.rep(string.char(120,21,77,4,5,0,7,36,44,100),
math.floor(len/10)) math.floor(len/10))
str = str .. str10 str = str .. str10
remote "str = data:receive()" remote "str = data:receive()"
@ -221,7 +221,7 @@ function test_totaltimeoutreceive(len, tm, sl)
data:settimeout(tm, "total") data:settimeout(tm, "total")
local t = socket.gettime() local t = socket.gettime()
str, err, partial, elapsed = data:receive(2*len) str, err, partial, elapsed = data:receive(2*len)
check_timeout(tm, sl, elapsed, err, "receive", "total", check_timeout(tm, sl, elapsed, err, "receive", "total",
string.len(str or partial) == 2*len) string.len(str or partial) == 2*len)
end end
@ -241,7 +241,7 @@ function test_totaltimeoutsend(len, tm, sl)
data:settimeout(tm, "total") data:settimeout(tm, "total")
str = string.rep("a", 2*len) str = string.rep("a", 2*len)
total, err, partial, elapsed = data:send(str) total, err, partial, elapsed = data:send(str)
check_timeout(tm, sl, elapsed, err, "send", "total", check_timeout(tm, sl, elapsed, err, "send", "total",
total == 2*len) total == 2*len)
end end
@ -261,7 +261,7 @@ function test_blockingtimeoutreceive(len, tm, sl)
]], 2*tm, len, sl, sl)) ]], 2*tm, len, sl, sl))
data:settimeout(tm) data:settimeout(tm)
str, err, partial, elapsed = data:receive(2*len) str, err, partial, elapsed = data:receive(2*len)
check_timeout(tm, sl, elapsed, err, "receive", "blocking", check_timeout(tm, sl, elapsed, err, "receive", "blocking",
string.len(str or partial) == 2*len) string.len(str or partial) == 2*len)
end end
@ -294,10 +294,10 @@ function empty_connect()
data = server:accept() data = server:accept()
]] ]]
data, err = socket.connect("", port) data, err = socket.connect("", port)
if not data then if not data then
pass("ok") pass("ok")
data = socket.connect(host, port) data = socket.connect(host, port)
else else
pass("gethostbyname returns localhost on empty string...") pass("gethostbyname returns localhost on empty string...")
end end
end end
@ -331,7 +331,7 @@ function test_closed()
data:close() data:close()
data = nil data = nil
]], str)) ]], str))
-- try to get a line -- try to get a line
back, err, partial = data:receive() back, err, partial = data:receive()
if not err then fail("should have gotten 'closed'.") if not err then fail("should have gotten 'closed'.")
elseif err ~= "closed" then fail("got '"..err.."' instead of 'closed'.") elseif err ~= "closed" then fail("got '"..err.."' instead of 'closed'.")
@ -344,25 +344,25 @@ function test_closed()
data = nil data = nil
]] ]]
total, err, partial = data:send(string.rep("ugauga", 100000)) total, err, partial = data:send(string.rep("ugauga", 100000))
if not err then if not err then
pass("failed: output buffer is at least %d bytes long!", total) pass("failed: output buffer is at least %d bytes long!", total)
elseif err ~= "closed" then elseif err ~= "closed" then
fail("got '"..err.."' instead of 'closed'.") fail("got '"..err.."' instead of 'closed'.")
else else
pass("graceful 'closed' received after %d bytes were sent", partial) pass("graceful 'closed' received after %d bytes were sent", partial)
end end
end end
------------------------------------------------------------------------ ------------------------------------------------------------------------
function test_selectbugs() function test_selectbugs()
local r, s, e = socket.select(nil, nil, 0.1) local r, s, e = socket.select(nil, nil, 0.1)
assert(type(r) == "table" and type(s) == "table" and assert(type(r) == "table" and type(s) == "table" and
(e == "timeout" or e == "error")) (e == "timeout" or e == "error"))
pass("both nil: ok") pass("both nil: ok")
local udp = socket.udp() local udp = socket.udp()
udp:close() udp:close()
r, s, e = socket.select({ udp }, { udp }, 0.1) r, s, e = socket.select({ udp }, { udp }, 0.1)
assert(type(r) == "table" and type(s) == "table" and assert(type(r) == "table" and type(s) == "table" and
(e == "timeout" or e == "error")) (e == "timeout" or e == "error"))
pass("closed sockets: ok") pass("closed sockets: ok")
e = pcall(socket.select, "wrong", 1, 0.1) e = pcall(socket.select, "wrong", 1, 0.1)
@ -380,7 +380,7 @@ function accept_timeout()
local t = socket.gettime() local t = socket.gettime()
s:settimeout(1) s:settimeout(1)
local c, e = s:accept() local c, e = s:accept()
assert(not c, "should not accept") assert(not c, "should not accept")
assert(e == "timeout", string.format("wrong error message (%s)", e)) assert(e == "timeout", string.format("wrong error message (%s)", e))
t = socket.gettime() - t t = socket.gettime() - t
assert(t < 2, string.format("took to long to give up (%gs)", t)) assert(t < 2, string.format("took to long to give up (%gs)", t))
@ -398,9 +398,9 @@ function connect_timeout()
local t = socket.gettime() local t = socket.gettime()
local r, e = c:connect("127.0.0.2", 80) local r, e = c:connect("127.0.0.2", 80)
assert(not r, "should not connect") assert(not r, "should not connect")
assert(socket.gettime() - t < 2, "took too long to give up.") assert(socket.gettime() - t < 2, "took too long to give up.")
c:close() c:close()
print("ok") print("ok")
end end
------------------------------------------------------------------------ ------------------------------------------------------------------------
@ -463,9 +463,9 @@ function getstats_test()
data:receive(c) data:receive(c)
t = t + c t = t + c
local r, s, a = data:getstats() local r, s, a = data:getstats()
assert(r == t, "received count failed" .. tostring(r) assert(r == t, "received count failed" .. tostring(r)
.. "/" .. tostring(t)) .. "/" .. tostring(t))
assert(s == t, "sent count failed" .. tostring(s) assert(s == t, "sent count failed" .. tostring(s)
.. "/" .. tostring(t)) .. "/" .. tostring(t))
end end
print("ok") print("ok")
@ -473,7 +473,7 @@ end
------------------------------------------------------------------------ ------------------------------------------------------------------------
function test_nonblocking(size) function test_nonblocking(size)
reconnect() reconnect()
print("Testing " .. 2*size .. " bytes") print("Testing " .. 2*size .. " bytes")
remote(string.format([[ remote(string.format([[

View File

@ -9,7 +9,7 @@ ack = "\n";
while 1 do while 1 do
print("server: waiting for client connection..."); print("server: waiting for client connection...");
control = assert(server:accept()); control = assert(server:accept());
while 1 do while 1 do
command = assert(control:receive()); command = assert(control:receive());
assert(control:send(ack)); assert(control:send(ack));
((loadstring or load)(command))(); ((loadstring or load)(command))();