local a=require(script.Parent.TestEnum)local b=require(script.Parent.Expectation)local function p(p,c)local J={}if c then if type(c)~="\116\097\098\108\101"then error(("\066\097\100 \097\114\103\117\109\101\110\116 \035\050 \116\111 \110\101\119\069\110\118\105\114\111\110\109\101\110\116\046 \069\120\112\101\099\116\101\100 \116\097\098\108\101\044 \103\111\116 \037\115"):format(typeof(c)),2)end for a,b in pairs(c)do J[a]=b end end local function M(b,c,J,M)local j=p:addChild(b,J,M)j.callback=c if J==a.NodeType.Describe then j:expand()end return j end function J.describeFOCUS(b,p)M(b,p,a.NodeType.Describe,a.NodeModifier.Focus)end function J.describeSKIP(b,p)M(b,p,a.NodeType.Describe,a.NodeModifier.Skip)end function J.describe(b,p,c)M(b,p,a.NodeType.Describe,a.NodeModifier.None)end function J.itFOCUS(b,p)M(b,p,a.NodeType.It,a.NodeModifier.Focus)end function J.itSKIP(b,p)M(b,p,a.NodeType.It,a.NodeModifier.Skip)end function J.itFIXME(b,p)local c=M(b,p,a.NodeType.It,a.NodeModifier.Skip)warn("\070\073\088\077\069\058 \098\114\111\107\101\110 \116\101\115\116",c:getFullName())end function J.it(b,p,c)M(b,p,a.NodeType.It,a.NodeModifier.None)end local j=0 local Q={[a.NodeType.BeforeAll]="\098\101\102\111\114\101\065\108\108";[a.NodeType.AfterAll]="\097\102\116\101\114\065\108\108";[a.NodeType.BeforeEach]="\098\101\102\111\114\101\069\097\099\104";[a.NodeType.AfterEach]="\097\102\116\101\114\069\097\099\104"}for b,p in pairs(Q)do J[p]=function(c)M(p..("\095"..tostring(j)),c,b,a.NodeModifier.None)j=j+1 end end function J.FIXME(b)warn("\070\073\088\077\069\058 \098\114\111\107\101\110 \116\101\115\116",p:getFullName(),b or"")p.modifier=a.NodeModifier.Skip end function J.FOCUS()p.modifier=a.NodeModifier.Focus end function J.SKIP()p.modifier=a.NodeModifier.Skip end function J.HACK_NO_XPCALL()warn("\072\065\067\075\095\078\079\095\088\080\067\065\076\076 \105\115 \100\101\112\114\101\099\097\116\101\100\046 \073\116 \105\115 \110\111\119 \115\097\102\101 \116\111 \121\105\101\108\100 \105\110 \097\110 \120\112\099\097\108\108\044 \115\111 \116\104\105\115 \105\115 \110\111 \108\111\110\103\101\114 \110\101\099\101\115\115\097\114\121\046 \073\116 \099\097\110 \098\101 \115\097\102\101\108\121 \100\101\108\101\116\101\100\046")end J.fit=J.itFOCUS J.xit=J.itSKIP J.fdescribe=J.describeFOCUS J.xdescribe=J.describeSKIP J.expect=setmetatable({extend=function(...)error("\067\097\110\110\111\116 \099\097\108\108 \"\101\120\112\101\099\116\046\101\120\116\101\110\100\" \102\114\111\109 \119\105\116\104\105\110 \097 \"\100\101\115\099\114\105\098\101\" \110\111\100\101\046")end},{__call=function(a,...)return b.new(...)end})return J end local c={}c.__index=c function c.new(b,J,M,j)j=j or a.NodeModifier.None local Q={plan=b,phrase=J;type=M;modifier=j,children={};callback=nil,parent=nil}Q.environment=p(Q,b.extraEnvironment)return setmetatable(Q,c)end local function J(b,p,c)if p and(c==nil or c==a.NodeModifier.None)then if b:match(p)then return a.NodeModifier.Focus else return a.NodeModifier.Skip end end return c end function c.addChild(j,b,p,M)if p==a.NodeType.It then for a,p in pairs(j.children)do if p.phrase==b then error("\068\117\112\108\105\099\097\116\101 \105\116 \098\108\111\099\107 \102\111\117\110\100\058 "..p:getFullName())end end end local Q=j:getFullName()..(" "..b)M=J(Q,j.plan.testNamePattern,M)local D=c.new(j.plan,b,p,M)D.parent=j table.insert(j.children,D)return D end function c.getFullName(a)if a.parent then local b=a.parent:getFullName()if b then return b..(" "..a.phrase)end end return a.phrase end function c.expand(a)local b=getfenv(a.callback)local p=setmetatable({},{__index=b})for a,b in pairs(a.environment)do p[a]=b end p.script=b.script setfenv(a.callback,p)local c,J=xpcall(a.callback,function(a)return debug.traceback(tostring(a),2)end)if not c then a.loadError=J end end local M={}M.__index=M function M.new(a,b)local p={children={};testNamePattern=a;extraEnvironment=b}return setmetatable(p,M)end function M.addChild(M,a,b,p)p=J(a,M.testNamePattern,p)local j=c.new(M,a,b,p)table.insert(M.children,j)return j end function M.addRoot(c,b,p)local J=c for p=#b,1,-1 do local c=nil for a,J in ipairs(J.children)do if J.phrase==b[p]then c=J break end end if c==nil then c=J:addChild(b[p],a.NodeType.Describe)end J=c end J.callback=p J:expand()end function M.visitAllNodes(c,a,b,p)b=b or c p=p or 0 for b,J in ipairs(b.children)do a(J,p)c:visitAllNodes(a,J,p+1)end end function M.visualize(a)local b={}a:visitAllNodes(function(a,p)table.insert(b,(" "):rep(3*p)..a.phrase)end)return table.concat(b,"\n")end function M.findNodes(b,a)local p={}b:visitAllNodes(function(b)if a(b)then table.insert(p,b)end end)return p end return M
--[[
	Represents a tree of tests that have been loaded but not necessarily
	executed yet.

	TestPlan objects are produced by TestPlanner.
]]

local TestEnum = require(script.Parent.TestEnum)
local Expectation = require(script.Parent.Expectation)

local function newEnvironment(currentNode, extraEnvironment)
	local env = {}

	if extraEnvironment then
		if type(extraEnvironment) ~= "table" then
			error(("Bad argument #2 to newEnvironment. Expected table, got %s"):format(
				typeof(extraEnvironment)), 2)
		end

		for key, value in pairs(extraEnvironment) do
			env[key] = value
		end
	end

	local function addChild(phrase, callback, nodeType, nodeModifier)
		local node = currentNode:addChild(phrase, nodeType, nodeModifier)
		node.callback = callback
		if nodeType == TestEnum.NodeType.Describe then
			node:expand()
		end
		return node
	end

	function env.describeFOCUS(phrase, callback)
		addChild(phrase, callback, TestEnum.NodeType.Describe, TestEnum.NodeModifier.Focus)
	end

	function env.describeSKIP(phrase, callback)
		addChild(phrase, callback, TestEnum.NodeType.Describe, TestEnum.NodeModifier.Skip)
	end

	function env.describe(phrase, callback, nodeModifier)
		addChild(phrase, callback, TestEnum.NodeType.Describe, TestEnum.NodeModifier.None)
	end

	function env.itFOCUS(phrase, callback)
		addChild(phrase, callback, TestEnum.NodeType.It, TestEnum.NodeModifier.Focus)
	end

	function env.itSKIP(phrase, callback)
		addChild(phrase, callback, TestEnum.NodeType.It, TestEnum.NodeModifier.Skip)
	end

	function env.itFIXME(phrase, callback)
		local node = addChild(phrase, callback, TestEnum.NodeType.It, TestEnum.NodeModifier.Skip)
		warn("FIXME: broken test", node:getFullName())
	end

	function env.it(phrase, callback, nodeModifier)
		addChild(phrase, callback, TestEnum.NodeType.It, TestEnum.NodeModifier.None)
	end

	-- Incrementing counter used to ensure that beforeAll, afterAll, beforeEach, afterEach have unique phrases
	local lifecyclePhaseId = 0

	local lifecycleHooks = {
		[TestEnum.NodeType.BeforeAll] = "beforeAll",
		[TestEnum.NodeType.AfterAll] = "afterAll",
		[TestEnum.NodeType.BeforeEach] = "beforeEach",
		[TestEnum.NodeType.AfterEach] = "afterEach"
	}

	for nodeType, name in pairs(lifecycleHooks) do
		env[name] = function(callback)
			addChild(name .. "_" .. tostring(lifecyclePhaseId), callback, nodeType, TestEnum.NodeModifier.None)
			lifecyclePhaseId = lifecyclePhaseId + 1
		end
	end

	function env.FIXME(optionalMessage)
		warn("FIXME: broken test", currentNode:getFullName(), optionalMessage or "")

		currentNode.modifier = TestEnum.NodeModifier.Skip
	end

	function env.FOCUS()
		currentNode.modifier = TestEnum.NodeModifier.Focus
	end

	function env.SKIP()
		currentNode.modifier = TestEnum.NodeModifier.Skip
	end

	--[[
		This function is deprecated. Calling it is a no-op beyond generating a
		warning.
	]]
	function env.HACK_NO_XPCALL()
		warn("HACK_NO_XPCALL is deprecated. It is now safe to yield in an " ..
			"xpcall, so this is no longer necessary. It can be safely deleted.")
	end

	env.fit = env.itFOCUS
	env.xit = env.itSKIP
	env.fdescribe = env.describeFOCUS
	env.xdescribe = env.describeSKIP

	env.expect = setmetatable({
		extend = function(...)
			error("Cannot call \"expect.extend\" from within a \"describe\" node.")
		end,
	}, {
		__call = function(_self, ...)
			return Expectation.new(...)
		end,
	})

	return env
end

local TestNode = {}
TestNode.__index = TestNode

--[[
	Create a new test node. A pointer to the test plan, a phrase to describe it
	and the type of node it is are required. The modifier is optional and will
	be None if left blank.
]]
function TestNode.new(plan, phrase, nodeType, nodeModifier)
	nodeModifier = nodeModifier or TestEnum.NodeModifier.None

	local node = {
		plan = plan,
		phrase = phrase,
		type = nodeType,
		modifier = nodeModifier,
		children = {},
		callback = nil,
		parent = nil,
	}

	node.environment = newEnvironment(node, plan.extraEnvironment)
	return setmetatable(node, TestNode)
end

local function getModifier(name, pattern, modifier)
	if pattern and (modifier == nil or modifier == TestEnum.NodeModifier.None) then
		if name:match(pattern) then
			return TestEnum.NodeModifier.Focus
		else
			return TestEnum.NodeModifier.Skip
		end
	end
	return modifier
end

function TestNode:addChild(phrase, nodeType, nodeModifier)
	if nodeType == TestEnum.NodeType.It then
		for _, child in pairs(self.children) do
			if child.phrase == phrase then
				error("Duplicate it block found: " .. child:getFullName())
			end
		end
	end

	local childName = self:getFullName() .. " " .. phrase
	nodeModifier = getModifier(childName, self.plan.testNamePattern, nodeModifier)
	local child = TestNode.new(self.plan, phrase, nodeType, nodeModifier)
	child.parent = self
	table.insert(self.children, child)
	return child
end

--[[
	Join the names of all the nodes back to the parent.
]]
function TestNode:getFullName()
	if self.parent then
		local parentPhrase = self.parent:getFullName()
		if parentPhrase then
			return parentPhrase .. " " .. self.phrase
		end
	end
	return self.phrase
end

--[[
	Expand a node by setting its callback environment and then calling it. Any
	further it and describe calls within the callback will be added to the tree.
]]
function TestNode:expand()
	local originalEnv = getfenv(self.callback)
	local callbackEnv = setmetatable({}, { __index = originalEnv })
	for key, value in pairs(self.environment) do
		callbackEnv[key] = value
	end
	-- Copy 'script' directly to new env to make Studio debugger happy.
	-- Studio debugger does not look into __index, because of security reasons
	callbackEnv.script = originalEnv.script
	setfenv(self.callback, callbackEnv)

	local success, result = xpcall(self.callback, function(message)
		return debug.traceback(tostring(message), 2)
	end)

	if not success then
		self.loadError = result
	end
end

local TestPlan = {}
TestPlan.__index = TestPlan

--[[
	Create a new, empty TestPlan.
]]
function TestPlan.new(testNamePattern, extraEnvironment)
	local plan = {
		children = {},
		testNamePattern = testNamePattern,
		extraEnvironment = extraEnvironment,
	}

	return setmetatable(plan, TestPlan)
end

--[[
	Add a new child under the test plan's root node.
]]
function TestPlan:addChild(phrase, nodeType, nodeModifier)
	nodeModifier = getModifier(phrase, self.testNamePattern, nodeModifier)
	local child = TestNode.new(self, phrase, nodeType, nodeModifier)
	table.insert(self.children, child)
	return child
end

--[[
	Add a new describe node with the given method as a callback. Generates or
	reuses all the describe nodes along the path.
]]
function TestPlan:addRoot(path, method)
	local curNode = self
	for i = #path, 1, -1 do
		local nextNode = nil

		for _, child in ipairs(curNode.children) do
			if child.phrase == path[i] then
				nextNode = child
				break
			end
		end

		if nextNode == nil then
			nextNode = curNode:addChild(path[i], TestEnum.NodeType.Describe)
		end

		curNode = nextNode
	end

	curNode.callback = method
	curNode:expand()
end

--[[
	Calls the given callback on all nodes in the tree, traversed depth-first.
]]
function TestPlan:visitAllNodes(callback, root, level)
	root = root or self
	level = level or 0

	for _, child in ipairs(root.children) do
		callback(child, level)

		self:visitAllNodes(callback, child, level + 1)
	end
end

--[[
	Visualizes the test plan in a simple format, suitable for debugging the test
	plan's structure.
]]
function TestPlan:visualize()
	local buffer = {}
	self:visitAllNodes(function(node, level)
		table.insert(buffer, (" "):rep(3 * level) .. node.phrase)
	end)
	return table.concat(buffer, "\n")
end

--[[
	Gets a list of all nodes in the tree for which the given callback returns
	true.
]]
function TestPlan:findNodes(callback)
	local results = {}
	self:visitAllNodes(function(node)
		if callback(node) then
			table.insert(results, node)
		end
	end)
	return results
end

return TestPlan
