Merge branch 'develop' into hairlessbear-quest_invite_modal_on_user_sync

This commit is contained in:
Blade Barringer
2015-06-14 16:33:38 -05:00
679 changed files with 14883 additions and 11486 deletions
+100
View File
@@ -0,0 +1,100 @@
'use strict'
diff = require("deep-diff")
Group = require("../../website/src/models/group").model
app = require("../../website/src/server")
describe "Chat", ->
group = undefined
before (done) ->
async.waterfall [
(cb) ->
registerNewUser(cb, true)
(user, cb) ->
request.post(baseURL + "/groups").send(
name: "TestGroup"
type: "party"
).end (res) ->
expectCode res, 200
group = res.body
expect(group.members.length).to.equal 1
expect(group.leader).to.equal user._id
cb()
], done
chat = undefined
it "posts a message to party chat", (done) ->
msg = "TestMsg"
request.post(baseURL + "/groups/" + group._id + "/chat?message=" + msg).end (res) ->
expectCode res, 200
chat = res.body.message
expect(chat.id).to.be.ok
expect(chat.text).to.equal msg
expect(chat.timestamp).to.be.exist
expect(chat.likes).to.be.empty
expect(chat.flags).to.be.empty
expect(chat.flagCount).to.equal 0
expect(chat.uuid).to.be.exist
expect(chat.contributor).to.be.empty
expect(chat.backer).to.be.empty
expect(chat.uuid).to.equal user._id
expect(chat.user).to.equal user.profile.name
done()
it "does not post an empty message", (done) ->
msg = ""
request.post(baseURL + "/groups/" + group._id + "/chat?message=" + msg).send(
).end (res) ->
expectCode res, 400
expect(res.body.err).to.equal 'You cannot send a blank message'
done()
it "can not like own chat message", (done) ->
request.post(baseURL + "/groups/" + group._id + "/chat/" + chat.id + "/like").send(
).end (res) ->
expectCode res, 401
body = res.body
expect(body.err).to.equal "Can't like your own message. Don't be that person."
done()
it "can not flag own message", (done) ->
request.post(baseURL + "/groups/" + group._id + "/chat/" + chat.id + "/flag").send(
).end (res) ->
expectCode res, 401
body = res.body
expect(body.err).to.equal "Can't report your own message."
done()
it "gets chat messages from party chat", (done) ->
request.get(baseURL + "/groups/" + group._id + "/chat").send(
).end (res) ->
expectCode res, 200
message = res.body[0]
expect(message.id).to.equal chat.id
expect(message.timestamp).to.equal chat.timestamp
expect(message.likes).to.deep.equal chat.likes
expect(message.flags).to.deep.equal chat.flags
expect(message.flagCount).to.equal chat.flagCount
expect(message.uuid).to.equal chat.uuid
expect(message.contributor).to.deep.equal chat.contributor
expect(message.backer).to.deep.equal chat.backer
expect(message.user).to.equal chat.user
done()
it "deletes a chat messages from party chat", (done) ->
request.del(baseURL + "/groups/" + group._id + "/chat/" + chat.id).send(
).end (res) ->
expectCode res, 204
expect(res.body).to.be.empty
done()
it "can not delete already deleted message", (done) ->
request.del(baseURL + "/groups/" + group._id + "/chat/" + chat.id).send(
).end (res) ->
expectCode res, 404
body = res.body
expect(body.err).to.equal "Message not found!"
done()
+268 -514
View File
@@ -5,560 +5,314 @@ diff = require("deep-diff")
Group = require("../../website/src/models/group").model
app = require("../../website/src/server")
describe "Groups", ->
describe "Guilds", ->
describe "Guilds", ->
context "creating groups", ->
before (done) ->
registerNewUser ->
User.findByIdAndUpdate user._id,
$set:
"balance": 4
"balance": 10
, (err, _user) ->
done()
, true
describe "Private Guilds", ->
guild = undefined
before (done) ->
it "can create a public guild", (done) ->
request.post(baseURL + "/groups").send(
name: "TestGroup"
type: "guild",
privacy: "public"
).end (res) ->
expectCode res, 200
guild = res.body
expect(guild.members.length).to.equal 1
expect(guild.leader).to.equal user._id
done()
it "can create a private guild", (done) ->
request.post(baseURL + "/groups").send(
name: "TestGroup"
type: "guild",
privacy: "private"
).end (res) ->
expectCode res, 200
guild = res.body
expect(guild.members.length).to.equal 1
expect(guild.leader).to.equal user._id
done()
it "prevents user from creating a guild when the user has 0 gems", (done) ->
registerNewUser (err, user_with_0_gems) ->
request.post(baseURL + "/groups").send(
name: "TestPrivateGroup"
type: "guild"
privacy: "private"
).end (res) ->
expectCode res, 200
guild = res.body
expect(guild.members.length).to.equal 1
expect(guild.leader).to.equal user._id
#Add members to guild
async.waterfall [
(cb) ->
registerManyUsers 15, cb
(_members, cb) ->
members = _members
joinGuild = (member, callback) ->
request.post(baseURL + "/groups/" + guild._id + "/join")
.set("X-API-User", member._id)
.set("X-API-Key", member.apiToken)
.end ->
callback(null, null)
async.map members, joinGuild, (err, results) -> cb()
], done
it "includes user in private group member list when user is a member", (done) ->
request.get(baseURL + "/groups/" + guild._id)
name: "TestGroup"
type: "guild",
)
.set("X-API-User", user_with_0_gems._id)
.set("X-API-Key", user_with_0_gems.apiToken)
.end (res) ->
g = res.body
userInGroup = _.find g.members, (member) -> return member._id == user._id
expect(userInGroup).to.exist
expectCode res, 401
done()
, false
context "get guilds", ->
guild = undefined
beforeEach (done)->
request.post(baseURL + "/groups").send(
name: "TestGroup2"
type: "guild"
).end (res) ->
guild = res.body
done()
it "can find a guild", (done) ->
request.get(baseURL + "/groups/" + guild._id)
.end (res) ->
expectCode res, 200
expect(res.body._id).to.equal res.body._id
done()
it "excludes user from viewing private group member list when user is not a member", (done) ->
request.post(baseURL + "/groups/" + guild._id + "/leave")
.end (res) ->
request.get(baseURL + "/groups/" + guild._id)
.end (res) ->
expect res, 404
done()
describe "Public Guilds", ->
guild = undefined
before (done) ->
request.post(baseURL + "/groups").send(
name: "TestPublicGroup"
type: "guild"
privacy: "public"
).end (res) ->
it "transforms members array to an arrray of user objects", (done) ->
request.get(baseURL + "/groups/" + guild._id)
.end (res) ->
expectCode res, 200
guild = res.body
expect(guild.members.length).to.equal 1
expect(guild.leader).to.equal user._id
#Add members to guild
async.waterfall [
(cb) ->
registerManyUsers 15, cb
members = res.body.members
# @TODO: would be more instructive if it had more members in guild :(
_(members).each (member) ->
expect(member).to.be.an 'object'
expect(member.profile.name).to.exist
done()
(_members, cb) ->
members = _members
it "transforms leader id to a user object", (done) ->
request.get(baseURL + "/groups/" + guild._id)
.end (res) ->
expectCode res, 200
leader = res.body.leader
expect(leader).to.be.an 'object'
expect(leader.profile.name).to.exist
done()
joinGuild = (member, callback) ->
request.post(baseURL + "/groups/" + guild._id + "/join")
.set("X-API-User", member._id)
.set("X-API-Key", member.apiToken)
.end ->
callback(null, null)
it "can list guilds", (done) ->
request.get(baseURL + "/groups").send()
.end (res) ->
expectCode res, 200
guild = res.body[0]
expect(guild).to.exist
done()
async.map members, joinGuild, (err, results) -> cb()
], done
context "updating groups", ->
groupToUpdate = undefined
before (done) ->
request.post(baseURL + "/groups").send(
name: "TestGroup"
type: "guild"
description: "notUpdatedDesc"
).end (res) ->
groupToUpdate = res.body
done()
context "is a member", ->
before (done) ->
registerNewUser ->
request.post(baseURL + "/groups/" + guild._id + "/join")
.end ->
done()
, true
it "prevents user from updating a party when they aren't the leader", (done) ->
registerNewUser (err, tmpUser) ->
request.post(baseURL + "/groups/" + groupToUpdate._id).send(
name: "TestGroupName"
description: "updatedDesc"
)
.set("X-API-User", tmpUser._id)
.set("X-API-Key", tmpUser.apiToken)
.end (res) ->
expectCode res, 401
expect(res.body.err).to.equal "Only the group leader can update the group!"
done()
, false
it "includes user in public group member list", (done) ->
it "allows user to update a group", (done) ->
request.post(baseURL + "/groups/" + groupToUpdate._id).send(
description: "updatedDesc"
)
.end (res) ->
expectCode res, 204
request.get(baseURL + "/groups/" + groupToUpdate._id).send()
.end (res) ->
updatedGroup = res.body
expect(updatedGroup.description).to.equal "updatedDesc"
done()
request.get(baseURL + "/groups/" + guild._id)
context "leaving groups", ->
it "can leave a guild", (done) ->
guildToLeave = undefined
request.post(baseURL + "/groups").send(
name: "TestGroupToLeave"
type: "guild"
).end (res) ->
guildToLeave = res.body
request.post(baseURL + "/groups/" + guildToLeave._id + "/leave")
.send()
.end (res) ->
expectCode res, 204
done()
context "removing users groups", ->
it "allows guild leaders to remove a member", (done) ->
guildToRemoveMember = undefined
members = undefined
userToRemove = undefined
request.post(baseURL + "/groups").send(
name: "TestGuildToRemoveMember"
type: "guild"
).end (res) ->
guildToRemoveMember = res.body
#Add members to guild
async.waterfall [
(cb) ->
registerManyUsers 1, cb
(_members, cb) ->
userToRemove = _members[0]
members = _members
inviteURL = baseURL + "/groups/" + guildToRemoveMember._id + "/invite"
request.post(inviteURL).send(
uuids: [userToRemove._id]
)
.end ->
cb()
(cb) ->
request.post(baseURL + "/groups/" + guildToRemoveMember._id + "/join")
.set("X-API-User", userToRemove._id)
.set("X-API-Key", userToRemove.apiToken)
.end (res) ->
cb()
(cb) ->
request.post(baseURL + "/groups/" + guildToRemoveMember._id + "/removeMember?uuid=" + userToRemove._id)
.send().end (res) ->
expectCode res, 204
cb()
(cb) ->
request.get(baseURL + "/groups/" + guildToRemoveMember._id)
.send()
.end (res) ->
g = res.body
expect(g.members.length).to.equal 15
userInGroup = _.find g.members, (member) -> return member._id == user._id
expect(userInGroup).to.be.ok
done()
userInGroup = _.find g.members, (member) -> return member._id == userToRemove._id
expect(userInGroup).to.not.exist
cb()
], done
context "is not a member", ->
describe "Private Guilds", ->
guild = undefined
before (done) ->
request.post(baseURL + "/groups").send(
name: "TestPrivateGroup"
type: "guild"
privacy: "private"
).end (res) ->
expectCode res, 200
guild = res.body
expect(guild.members.length).to.equal 1
expect(guild.leader).to.equal user._id
#Add members to guild
async.waterfall [
(cb) ->
registerManyUsers 15, cb
before (done) ->
registerNewUser done, true
(_members, cb) ->
members = _members
it "excludes user in public group member list", (done) ->
joinGuild = (member, callback) ->
request.post(baseURL + "/groups/" + guild._id + "/join")
.set("X-API-User", member._id)
.set("X-API-Key", member.apiToken)
.end ->
callback(null, null)
async.map members, joinGuild, (err, results) -> cb()
], done
it "includes user in private group member list when user is a member", (done) ->
request.get(baseURL + "/groups/" + guild._id)
.end (res) ->
g = res.body
userInGroup = _.find g.members, (member) -> return member._id == user._id
expect(userInGroup).to.exist
done()
it "excludes user from viewing private group member list when user is not a member", (done) ->
request.post(baseURL + "/groups/" + guild._id + "/leave")
.end (res) ->
request.get(baseURL + "/groups/" + guild._id)
.end (res) ->
g = res.body
expect(g.members.length).to.equal 15
userInGroup = _.find g.members, (member) -> return member._id == user._id
expect(userInGroup).to.not.be.ok
done()
.end (res) ->
expect res, 404
done()
describe "Party", ->
group = undefined
describe "Public Guilds", ->
guild = undefined
before (done) ->
async.waterfall [
(cb) ->
registerNewUser(cb, true)
, (user, cb) ->
registerNewUser ->
User.findByIdAndUpdate user._id, {$set: { "balance": 10 } }, (err, _user) ->
cb()
, true
(cb) ->
request.post(baseURL + "/groups").send(
name: "TestGroup"
type: "party"
name: "TestPublicGroup"
type: "guild"
privacy: "public"
).end (res) ->
expectCode res, 200
group = res.body
expect(group.members.length).to.equal 1
expect(group.leader).to.equal user._id
done()
]
guild = res.body
expect(guild.members.length).to.equal 1
expect(guild.leader).to.equal user._id
#Add members to guild
cb()
it "can be found by querying for party", (done) ->
request.get(baseURL + "/groups/").send(
type: "party"
).end (res) ->
expectCode res, 200
(cb) ->
registerManyUsers 15, cb
party = res.body[0]
expect(party._id).to.equal group._id
expect(party.leader).to.equal user._id
expect(party.name).to.equal group.name
expect(party.quest).to.deep.equal { progress: {} }
expect(party.memberCount).to.equal group.memberCount
done()
(_members, cb) ->
members = _members
describe "Chat", ->
chat = undefined
it "Posts a message to party chat", (done) ->
msg = "TestMsg"
request.post(baseURL + "/groups/" + group._id + "/chat?message=" + msg).send(
).end (res) ->
expectCode res, 200
chat = res.body.message
expect(chat.id).to.be.ok
expect(chat.text).to.equal msg
expect(chat.timestamp).to.be.ok
expect(chat.likes).to.be.empty
expect(chat.flags).to.be.empty
expect(chat.flagCount).to.equal 0
expect(chat.uuid).to.be.ok
expect(chat.contributor).to.be.empty
expect(chat.backer).to.be.empty
expect(chat.uuid).to.equal user._id
expect(chat.user).to.equal user.profile.name
done()
joinGuild = (member, callback) ->
request.post(baseURL + "/groups/" + guild._id + "/join")
.set("X-API-User", member._id)
.set("X-API-Key", member.apiToken)
.end ->
callback(null, null)
it "Does not post an empty message", (done) ->
msg = ""
request.post(baseURL + "/groups/" + group._id + "/chat?message=" + msg).send(
).end (res) ->
expectCode res, 400
expect(res.body.err).to.equal 'You cannot send a blank message'
done()
async.map members, joinGuild, (err, results) -> cb()
it "can not like own chat message", (done) ->
request.post(baseURL + "/groups/" + group._id + "/chat/" + chat.id + "/like").send(
).end (res) ->
expectCode res, 401
body = res.body
expect(body.err).to.equal "Can't like your own message. Don't be that person."
done()
], done
it "can not flag own message", (done) ->
request.post(baseURL + "/groups/" + group._id + "/chat/" + chat.id + "/flag").send(
).end (res) ->
expectCode res, 401
body = res.body
expect(body.err).to.equal "Can't report your own message."
done()
it "Gets chat messages from party chat", (done) ->
request.get(baseURL + "/groups/" + group._id + "/chat").send(
).end (res) ->
expectCode res, 200
message = res.body[0]
expect(message.id).to.equal chat.id
expect(message.timestamp).to.equal chat.timestamp
expect(message.likes).to.deep.equal chat.likes
expect(message.flags).to.deep.equal chat.flags
expect(message.flagCount).to.equal chat.flagCount
expect(message.uuid).to.equal chat.uuid
expect(message.contributor).to.deep.equal chat.contributor
expect(message.backer).to.deep.equal chat.backer
expect(message.user).to.equal chat.user
done()
it "Deletes a chat messages from party chat", (done) ->
request.del(baseURL + "/groups/" + group._id + "/chat/" + chat.id).send(
).end (res) ->
expectCode res, 204
expect(res.body).to.be.empty
done()
it "Can not delete already deleted message", (done) ->
request.del(baseURL + "/groups/" + group._id + "/chat/" + chat.id).send(
).end (res) ->
expectCode res, 404
body = res.body
expect(body.err).to.equal "Message not found!"
done()
describe "Quests", ->
party = undefined
participating = []
notParticipating = []
context "is a member", ->
before (done) ->
# Tavern boss, side-by-side
Group.update(
_id: "habitrpg"
,
$set:
quest:
key: "dilatory"
active: true
progress:
hp: shared.content.quests.dilatory.boss.hp
rage: 0
).exec()
registerNewUser ->
request.post(baseURL + "/groups/" + guild._id + "/join")
.end (res)->
done()
, true
# Tally some progress for later. Later we want to test that progress made before the quest began gets
# counted after the quest starts
async.waterfall [
(cb) ->
request.post(baseURL + '/user/tasks').send({
type: 'daily'
text: 'daily one'
}).end (res) ->
cb()
(cb) ->
request.post(baseURL + '/user/tasks').send({
type: 'daily'
text: 'daily two'
}).end (res) ->
cb()
(cb) ->
User.findByIdAndUpdate user._id,
$set:
"stats.lvl": 50
, (err, _user) ->
cb(null, _user)
(_user, cb) ->
user = _user
request.post(baseURL + "/user/batch-update").send([
{
op: "score"
params:
direction: "up"
id: user.dailys[0].id
}
{
op: "score"
params:
direction: "up"
id: user.dailys[0].id
}
{
op: "update"
body:
"stats.lvl": 50
}
]).end (res) ->
user = res.body
expect(user.party.quest.progress.up).to.be.above 0
it "includes user in public group member list", (done) ->
request.get(baseURL + "/groups/" + guild._id)
.end (res) ->
g = res.body
expect(g.members.length).to.equal 15
userInGroup = _.find g.members, (member) -> return member._id == user._id
expect(userInGroup).to.exist
done()
# Invite some members
async.waterfall [
# Register new users
(cb) ->
registerManyUsers 3, cb
context "is not a member", ->
before (done) ->
registerNewUser done, true
# Send them invitations
(_party, cb) ->
party = _party
inviteURL = baseURL + "/groups/" + group._id + "/invite"
async.parallel [
(cb2) ->
request.post(inviteURL).send(
uuids: [party[0]._id]
).end ->
cb2()
(cb2) ->
request.post(inviteURL).send(
uuids: [party[1]._id]
).end ->
cb2()
(cb2) ->
request.post(inviteURL).send(
uuids: [party[2]._id]
).end (res)->
cb2()
], cb
# Accept / Reject
(results, cb) ->
# series since they'll be modifying the same group record
series = _.reduce(party, (m, v, i) ->
m.push (cb2) ->
request.post(baseURL + "/groups/" + group._id + "/join").set("X-API-User", party[i]._id).set("X-API-Key", party[i].apiToken).end ->
cb2()
m
, [])
async.series series, cb
# Make sure the invites stuck
(whatever, cb) ->
Group.findById group._id, (err, g) ->
group = g
expect(g.members.length).to.equal 4
cb()
], ->
# Start the quest
async.waterfall [
(cb) ->
request.post(baseURL + "/groups/" + group._id + "/questAccept?key=vice3").end (res) ->
expectCode res, 400
User.findByIdAndUpdate user._id,
$set:
"items.quests.vice3": 1
, cb
(_user, cb) ->
request.post(baseURL + "/groups/" + group._id + "/questAccept?key=vice3").end (res) ->
expectCode res, 200
Group.findById group._id, cb
(_group, cb) ->
expect(_group.quest.key).to.equal "vice3"
expect(_group.quest.active).to.equal false
request.post(baseURL + "/groups/" + group._id + "/questAccept").set("X-API-User", party[0]._id).set("X-API-Key", party[0].apiToken).end ->
request.post(baseURL + "/groups/" + group._id + "/questAccept").set("X-API-User", party[1]._id).set("X-API-Key", party[1].apiToken).end (res) ->
request.post(baseURL + "/groups/" + group._id + "/questReject").set("X-API-User", party[2]._id).set("X-API-Key", party[2].apiToken).end (res) ->
group = res.body
expect(group.quest.active).to.equal true
cb()
], done
]
it "Casts a spell", (done) ->
mp = user.stats.mp
request.get(baseURL + "/members/" + party[0]._id).end (res) ->
party[0] = res.body
request.post(baseURL + "/user/class/cast/snowball?targetType=user&targetId=" + party[0]._id).end (res) ->
#expect(res.body.stats.mp).to.be.below(mp);
request.get(baseURL + "/members/" + party[0]._id).end (res) ->
member = res.body
expect(member.achievements.snowball).to.equal 1
expect(member.stats.buffs.snowball).to.exist
difference = diff(member, party[0])
expect(_.size(difference)).to.equal 2
# level up user so str is > 0
request.put(baseURL + "/user").send("stats.lvl": 5).end (res) ->
# Refill mana so user can cast
request.put(baseURL + "/user").send("stats.mp": 100).end (res) ->
request.post(baseURL + "/user/class/cast/valorousPresence?targetType=party").end (res) ->
request.get(baseURL + "/members/" + member._id).end (res) ->
expect(res.body.stats.buffs.str).to.be.above 0
expect(diff(res.body, member).length).to.equal 1
done()
it "Doesn't include people who aren't participating", (done) ->
request.get(baseURL + "/groups/" + group._id).end (res) ->
expect(_.size(res.body.quest.members)).to.equal 3
done()
xit "Hurts the boss", (done) ->
request.post(baseURL + "/user/batch-update").end (res) ->
user = res.body
up = user.party.quest.progress.up
expect(up).to.be.above 0
#{op:'score',params:{direction:'up',id:user.dailys[3].id}}, // leave one daily undone so Trapper hurts party
# set day to yesterday, cron will then be triggered on next action
request.post(baseURL + "/user/batch-update").send([
{
op: "score"
params:
direction: "up"
id: user.dailys[0].id
}
{
op: "update"
body:
lastCron: moment().subtract(1, "days")
}
]).end (res) ->
expect(res.body.party.quest.progress.up).to.be.above up
request.post(baseURL + "/user/batch-update").end ->
request.get(baseURL + "/groups/party").end (res) ->
# Check boss damage
async.waterfall [
(cb) ->
async.parallel [
#tavern boss
(cb2) ->
Group.findById "habitrpg",
quest: 1
, (err, tavern) ->
expect(tavern.quest.progress.hp).to.be.below shared.content.quests.dilatory.boss.hp
expect(tavern.quest.progress.rage).to.be.above 0
cb2()
# party boss
(cb2) ->
expect(res.body.quest.progress.hp).to.be.below shared.content.quests.vice3.boss.hp
_party = res.body.members
expect(_.find(_party,
_id: party[0]._id
).stats.hp).to.be.below 50
expect(_.find(_party,
_id: party[1]._id
).stats.hp).to.be.below 50
expect(_.find(_party,
_id: party[2]._id
).stats.hp).to.be 50
cb2()
], cb
# Kill the boss
(whatever, cb) ->
async.waterfall [
# tavern boss
(cb2) ->
expect(user.items.pets["MantisShrimp-Base"]).to.not.be.ok()
Group.update
_id: "habitrpg"
,
$set:
"quest.progress.hp": 0
, cb2
# party boss
(arg1, arg2, cb2) ->
expect(user.items.gear.owned.weapon_special_2).to.not.be.ok()
Group.findByIdAndUpdate group._id,
$set:
"quest.progress.hp": 0
, cb2
], cb
(_group, cb) ->
# set day to yesterday, cron will then be triggered on next action
request.post(baseURL + "/user/batch-update").send([
{
op: "score"
params:
direction: "up"
id: user.dailys[1].id
}
{
op: "update"
body:
lastCron: moment().subtract(1, "days")
}
]).end ->
cb()
(cb) ->
request.post(baseURL + "/user/batch-update").end (res) ->
cb null, res.body
(_user, cb) ->
# need to load the user again, since tavern boss does update after user's cron
User.findById _user._id, cb
(_user, cb) ->
user = _user
Group.findById group._id, cb
(_group, cb) ->
cummExp = shared.content.quests.vice3.drop.exp + shared.content.quests.dilatory.drop.exp
cummGp = shared.content.quests.vice3.drop.gp + shared.content.quests.dilatory.drop.gp
#//FIXME check that user got exp, but user is leveling up making the exp check difficult
# expect(user.stats.exp).to.be.above(cummExp);
# expect(user.stats.gp).to.be.above(cummGp);
async.parallel [
# Tavern Boss
(cb2) ->
Group.findById "habitrpg", (err, tavern) ->
#use an explicit get because mongoose wraps the null in an object
expect(_.isEmpty(tavern.get("quest"))).to.equal true
expect(user.items.pets["MantisShrimp-Base"]).to.equal 5
expect(user.items.mounts["MantisShrimp-Base"]).to.equal true
expect(user.items.eggs.Dragon).to.equal 2
expect(user.items.hatchingPotions.Shade).to.equal 2
cb2()
# Party Boss
(cb2) ->
#use an explicit get because mongoose wraps the null in an object
expect(_.isEmpty(_group.get("quest"))).to.equal true
expect(user.items.gear.owned.weapon_special_2).to.equal true
expect(user.items.eggs.Dragon).to.equal 2
expect(user.items.hatchingPotions.Shade).to.equal 2
# need to fetch users to get updated data
async.parallel [
(cb3) ->
User.findById party[0].id, (err, mbr) ->
expect(mbr.items.gear.owned.weapon_special_2).to.equal true
cb3()
(cb3) ->
User.findById party[1].id, (err, mbr) ->
expect(mbr.items.gear.owned.weapon_special_2).to.equal true
cb3()
(cb3) ->
User.findById party[2].id, (err, mbr) ->
expect(mbr.items.gear.owned.weapon_special_2).to.not.be.ok()
cb3()
], cb2
], cb
], done
it "excludes user in public group member list", (done) ->
request.get(baseURL + "/groups/" + guild._id)
.end (res) ->
g = res.body
expect(g.members.length).to.equal 15
userInGroup = _.find g.members, (member) -> return member._id == user._id
expect(userInGroup).to.not.exist
done()
+464
View File
@@ -0,0 +1,464 @@
'use strict'
diff = require("deep-diff")
Group = require("../../website/src/models/group").model
app = require("../../website/src/server")
describe "Party", ->
context "creating a party", ->
it "creates a party", (done) ->
async.waterfall [
(cb) ->
registerNewUser(cb, true)
(user, cb) ->
request.post(baseURL + "/groups").send(
name: "TestGroup"
type: "party"
).end (res) ->
expectCode res, 200
group = res.body
expect(group.members.length).to.equal 1
expect(group.leader).to.equal user._id
cb()
], done
it "prevents user from creating a second party", (done) ->
request.post(baseURL + "/groups").send(
name: "TestGroup"
type: "party"
).end (res) ->
expectCode res, 400
expect(res.body.err).to.equal "Already in a party, try refreshing."
done()
context "Searching for a party", ->
group = undefined
beforeEach (done) ->
async.waterfall [
(cb) ->
registerNewUser(cb, true)
(user, cb) ->
request.post(baseURL + "/groups").send(
name: "TestGroup"
type: "party"
).end (res) ->
expectCode res, 200
group = res.body
expect(group.members.length).to.equal 1
expect(group.leader).to.equal user._id
cb()
], done
it "can be found by querying for group type party", (done) ->
request.get(baseURL + "/groups/").send(
type: "party"
).end (res) ->
expectCode res, 200
party = _.find res.body, (g) -> return g._id == group._id
expect(party._id).to.equal group._id
expect(party.leader).to.equal user._id
expect(party.name).to.equal group.name
expect(party.quest).to.deep.equal { progress: {} }
expect(party.memberCount).to.equal group.memberCount
done()
context "joining a party", ->
group = undefined
beforeEach (done) ->
async.waterfall [
(cb) ->
registerNewUser(cb, true)
(user, cb) ->
request.post(baseURL + "/groups").send(
name: "TestGroup"
type: "party"
).end (res) ->
expectCode res, 200
group = res.body
expect(group.members.length).to.equal 1
expect(group.leader).to.equal user._id
cb()
], done
it "prevents user from joining a party when they haven't been invited", (done) ->
registerNewUser (err, user) ->
request.post(baseURL + "/groups/" + group._id + "/join").send()
.set("X-API-User", user._id)
.set("X-API-Key", user.apiToken)
.end (res) ->
expectCode res, 401
expect(res.body.err).to.equal "Can't join a group you're not invited to."
done()
, false
it "allows users to join a party when they have been invited", (done) ->
tmpUser = undefined
async.waterfall [
(cb) ->
registerNewUser(cb, false)
(user, cb) ->
tmpUser = user
inviteURL = baseURL + "/groups/" + group._id + "/invite"
request.post(inviteURL).send(
uuids: [tmpUser._id]
)
.end ->
cb()
(cb) ->
request.post(baseURL + "/groups/" + group._id + "/join")
.set("X-API-User", tmpUser._id)
.set("X-API-Key", tmpUser.apiToken)
.end (res) ->
expectCode res, 200
cb()
(cb) ->
Group.findById group._id, (err, grp) ->
expect(grp.members).to.include(tmpUser._id)
cb()
], done
context "Quests", ->
party = undefined
group = undefined
participating = []
notParticipating = []
before (done) ->
# Tavern boss, side-by-side
Group.update(
_id: "habitrpg"
,
$set:
quest:
key: "dilatory"
active: true
progress:
hp: shared.content.quests.dilatory.boss.hp
rage: 0
).exec()
# Tally some progress for later. Later we want to test that progress made before the quest began gets
# counted after the quest starts
async.waterfall [
(cb) ->
registerNewUser(cb, true)
(user, cb) ->
request.post(baseURL + "/groups").send(
name: "TestGroup"
type: "party"
).end (res) ->
expectCode res, 200
group = res.body
expect(group.members.length).to.equal 1
expect(group.leader).to.equal user._id
cb()
(cb) ->
request.post(baseURL + '/user/tasks').send({
type: 'daily'
text: 'daily one'
}).end (res) ->
cb()
(cb) ->
request.post(baseURL + '/user/tasks').send({
type: 'daily'
text: 'daily two'
}).end (res) ->
cb()
(cb) ->
User.findByIdAndUpdate user._id,
$set:
"stats.lvl": 50
, (err, _user) ->
cb(null, _user)
(_user, cb) ->
user = _user
request.post(baseURL + "/user/batch-update").send([
{
op: "score"
params:
direction: "up"
id: user.dailys[0].id
}
{
op: "score"
params:
direction: "up"
id: user.dailys[0].id
}
{
op: "update"
body:
"stats.lvl": 50
}
]).end (res) ->
user = res.body
expect(user.party.quest.progress.up).to.be.above 0
# Invite some members
async.waterfall [
# Register new users
(cb) ->
registerManyUsers 3, cb
# Send them invitations
(_party, cb) ->
party = _party
inviteURL = baseURL + "/groups/" + group._id + "/invite"
async.parallel [
(cb2) ->
request.post(inviteURL).send(
uuids: [party[0]._id]
).end ->
cb2()
(cb2) ->
request.post(inviteURL).send(
uuids: [party[1]._id]
).end ->
cb2()
(cb2) ->
request.post(inviteURL).send(
uuids: [party[2]._id]
).end (res)->
cb2()
], cb
# Accept / Reject
(results, cb) ->
# series since they'll be modifying the same group record
series = _.reduce(party, (m, v, i) ->
m.push (cb2) ->
request.post(baseURL + "/groups/" + group._id + "/join").set("X-API-User", party[i]._id).set("X-API-Key", party[i].apiToken).end ->
cb2()
m
, [])
async.series series, cb
# Make sure the invites stuck
(whatever, cb) ->
Group.findById group._id, (err, g) ->
group = g
expect(g.members.length).to.equal 4
cb()
], ->
# Start the quest
async.waterfall [
(cb) ->
request.post(baseURL + "/groups/" + group._id + "/questAccept?key=vice3").end (res) ->
expectCode res, 400
User.findByIdAndUpdate user._id,
$set:
"items.quests.vice3": 1
, cb
(_user, cb) ->
request.post(baseURL + "/groups/" + group._id + "/questAccept?key=vice3").end (res) ->
expectCode res, 200
Group.findById group._id, cb
(_group, cb) ->
expect(_group.quest.key).to.equal "vice3"
expect(_group.quest.active).to.equal false
request.post(baseURL + "/groups/" + group._id + "/questAccept").set("X-API-User", party[0]._id).set("X-API-Key", party[0].apiToken).end ->
request.post(baseURL + "/groups/" + group._id + "/questAccept").set("X-API-User", party[1]._id).set("X-API-Key", party[1].apiToken).end (res) ->
request.post(baseURL + "/groups/" + group._id + "/questReject").set("X-API-User", party[2]._id).set("X-API-Key", party[2].apiToken).end (res) ->
group = res.body
expect(group.quest.active).to.equal true
cb()
], done
]
it "Casts a spell", (done) ->
mp = user.stats.mp
request.get(baseURL + "/members/" + party[0]._id).end (res) ->
party[0] = res.body
request.post(baseURL + "/user/class/cast/snowball?targetType=user&targetId=" + party[0]._id).end (res) ->
#expect(res.body.stats.mp).to.be.below(mp);
request.get(baseURL + "/members/" + party[0]._id).end (res) ->
member = res.body
expect(member.achievements.snowball).to.equal 1
expect(member.stats.buffs.snowball).to.exist
difference = diff(member, party[0])
expect(_.size(difference)).to.equal 2
# level up user so str is > 0
request.put(baseURL + "/user").send("stats.lvl": 5).end (res) ->
# Refill mana so user can cast
request.put(baseURL + "/user").send("stats.mp": 100).end (res) ->
request.post(baseURL + "/user/class/cast/valorousPresence?targetType=party").end (res) ->
request.get(baseURL + "/members/" + member._id).end (res) ->
expect(res.body.stats.buffs.str).to.be.above 0
expect(diff(res.body, member).length).to.equal 1
done()
it "Doesn't include people who aren't participating", (done) ->
request.get(baseURL + "/groups/" + group._id).end (res) ->
expect(_.size(res.body.quest.members)).to.equal 3
done()
xit "Hurts the boss", (done) ->
request.post(baseURL + "/user/batch-update").end (res) ->
user = res.body
up = user.party.quest.progress.up
expect(up).to.be.above 0
#{op:'score',params:{direction:'up',id:user.dailys[3].id}}, // leave one daily undone so Trapper hurts party
# set day to yesterday, cron will then be triggered on next action
request.post(baseURL + "/user/batch-update").send([
{
op: "score"
params:
direction: "up"
id: user.dailys[0].id
}
{
op: "update"
body:
lastCron: moment().subtract(1, "days")
}
]).end (res) ->
expect(res.body.party.quest.progress.up).to.be.above up
request.post(baseURL + "/user/batch-update").end ->
request.get(baseURL + "/groups/party").end (res) ->
# Check boss damage
async.waterfall [
(cb) ->
async.parallel [
#tavern boss
(cb2) ->
Group.findById "habitrpg",
quest: 1
, (err, tavern) ->
expect(tavern.quest.progress.hp).to.be.below shared.content.quests.dilatory.boss.hp
expect(tavern.quest.progress.rage).to.be.above 0
cb2()
# party boss
(cb2) ->
expect(res.body.quest.progress.hp).to.be.below shared.content.quests.vice3.boss.hp
_party = res.body.members
expect(_.find(_party,
_id: party[0]._id
).stats.hp).to.be.below 50
expect(_.find(_party,
_id: party[1]._id
).stats.hp).to.be.below 50
expect(_.find(_party,
_id: party[2]._id
).stats.hp).to.be 50
cb2()
], cb
# Kill the boss
(whatever, cb) ->
async.waterfall [
# tavern boss
(cb2) ->
expect(user.items.pets["MantisShrimp-Base"]).to.not.be.ok()
Group.update
_id: "habitrpg"
,
$set:
"quest.progress.hp": 0
, cb2
# party boss
(arg1, arg2, cb2) ->
expect(user.items.gear.owned.weapon_special_2).to.not.be.ok()
Group.findByIdAndUpdate group._id,
$set:
"quest.progress.hp": 0
, cb2
], cb
(_group, cb) ->
# set day to yesterday, cron will then be triggered on next action
request.post(baseURL + "/user/batch-update").send([
{
op: "score"
params:
direction: "up"
id: user.dailys[1].id
}
{
op: "update"
body:
lastCron: moment().subtract(1, "days")
}
]).end ->
cb()
(cb) ->
request.post(baseURL + "/user/batch-update").end (res) ->
cb null, res.body
(_user, cb) ->
# need to load the user again, since tavern boss does update after user's cron
User.findById _user._id, cb
(_user, cb) ->
user = _user
Group.findById group._id, cb
(_group, cb) ->
cummExp = shared.content.quests.vice3.drop.exp + shared.content.quests.dilatory.drop.exp
cummGp = shared.content.quests.vice3.drop.gp + shared.content.quests.dilatory.drop.gp
#//FIXME check that user got exp, but user is leveling up making the exp check difficult
# expect(user.stats.exp).to.be.above(cummExp);
# expect(user.stats.gp).to.be.above(cummGp);
async.parallel [
# Tavern Boss
(cb2) ->
Group.findById "habitrpg", (err, tavern) ->
#use an explicit get because mongoose wraps the null in an object
expect(_.isEmpty(tavern.get("quest"))).to.equal true
expect(user.items.pets["MantisShrimp-Base"]).to.equal 5
expect(user.items.mounts["MantisShrimp-Base"]).to.equal true
expect(user.items.eggs.Dragon).to.equal 2
expect(user.items.hatchingPotions.Shade).to.equal 2
cb2()
# Party Boss
(cb2) ->
#use an explicit get because mongoose wraps the null in an object
expect(_.isEmpty(_group.get("quest"))).to.equal true
expect(user.items.gear.owned.weapon_special_2).to.equal true
expect(user.items.eggs.Dragon).to.equal 2
expect(user.items.hatchingPotions.Shade).to.equal 2
# need to fetch users to get updated data
async.parallel [
(cb3) ->
User.findById party[0].id, (err, mbr) ->
expect(mbr.items.gear.owned.weapon_special_2).to.equal true
cb3()
(cb3) ->
User.findById party[1].id, (err, mbr) ->
expect(mbr.items.gear.owned.weapon_special_2).to.equal true
cb3()
(cb3) ->
User.findById party[2].id, (err, mbr) ->
expect(mbr.items.gear.owned.weapon_special_2).to.not.be.ok()
cb3()
], cb2
], cb
], done
+49 -1
View File
@@ -1,4 +1,7 @@
'use strict'
#@TODO: Have to mock most things to get to the parts that
#call pushNotify. Consider refactoring group controller
#so things are easier to test
app = require("../../website/src/server")
rewire = require('rewire')
@@ -78,7 +81,6 @@ describe "Push-Notifications", ->
recipient = null
groups = rewire("../../website/src/controllers/groups")
groups.__set__('questStart', -> true)
groups.__set__('pushNotify', pushSpy)
before (done) ->
@@ -152,6 +154,7 @@ describe "Push-Notifications", ->
group = { _id: 'party-id', name: 'party-name', type: 'party', members: [user._id, recipient._id], invites: [], quest: {}}
user.items.quests.hedgehog = 5
group.save = (cb) -> cb(null, group)
group.markModified = -> true
req = {
body: { uuids: [recipient._id] }
query: { key: 'hedgehog' }
@@ -173,6 +176,51 @@ describe "Push-Notifications", ->
done()
, 100
it "sends a push notification to participating members when quest starts", (done) ->
group = { _id: 'party-id', name: 'party-name', type: 'party', members: [user._id, recipient._id], invites: []}
group.quest = {
key: 'hedgehog'
progress: { hp: 100 }
members: {}
}
group.quest.members[recipient._id] = true
group.save = (cb) -> cb(null, group)
group.markModified = -> true
req = {
body: { uuids: [recipient._id] }
query: { }
# force: true
}
res = {
locals: { group: group, user: user }
json: -> return true
}
userMock = {
findOne: (arg, arg2, cb) ->
cb(null, recipient)
update: (arg, arg2, cb) ->
cb(null, user)
}
groups.__set__('User', userMock)
groups.__set__('populateQuery',
(arg, arg2, arg3) ->
return {
exec: -> group.members
}
)
groups.questAccept req, res
setTimeout -> # Allow questAccept to finish
expect(pushSpy.sendNotify).to.have.been.calledTwice
expect(pushSpy.sendNotify).to.have.been.calledWith(
recipient,
'HabitRPG',
'Your Quest has Begun: The Hedgebeast'
)
done()
, 100
describe "Gifts", ->
recipient = null
+21
View File
@@ -97,6 +97,27 @@ describe "Todos", ->
expect(todo.value).to.equal 0
done()
it "Does not create a todo with an id that already exists", (done) ->
original_todo = {
type: "todo"
text: "original todo"
id: "custom-id"
}
duplicate_id_todo = {
type: "todo"
text: "not original todo"
id: "custom-id"
}
request.post(baseURL + "/user/tasks").send(
original_todo
).end (res) ->
request.post(baseURL + "/user/tasks").send(
duplicate_id_todo
).end (res) ->
expectCode res, 409
expect(res.body.err).to.eql('A task with that ID already exists.')
done()
describe "Updating todos", ->
it "Does not update id of todo", (done) ->
request.put(baseURL + "/user/tasks/" + todo.id).send(
+99 -7
View File
@@ -24,6 +24,7 @@ newUser = (addTasks=true)->
gear:
equipped: {}
costume: {}
owned: {}
party:
quest:
progress:
@@ -33,7 +34,8 @@ newUser = (addTasks=true)->
todos: []
rewards: []
flags: {}
achievements: {}
achievements:
ultimateGearSets: {}
contributor:
level: 2
@@ -157,7 +159,7 @@ describe 'User', ->
it 'handles perfect days', ->
user = newUser()
user.dailys = []
_.times 3, ->user.dailys.push shared.taskDefaults({type:'daily'})
_.times 3, ->user.dailys.push shared.taskDefaults({type:'daily', startDate: moment().subtract(7, 'days')})
cron = -> user.lastCron = moment().subtract(1,'days');user.fns.cron()
cron()
@@ -191,7 +193,7 @@ describe 'User', ->
user.preferences.sleep = true
cron = -> user.lastCron = moment().subtract(1, 'days');user.fns.cron()
user.dailys = []
_.times 2, -> user.dailys.push shared.taskDefaults({type:'daily'})
_.times 2, -> user.dailys.push shared.taskDefaults({type:'daily', startDate: moment().subtract(7, 'days')})
it 'remains in the inn on cron', ->
cron()
@@ -432,7 +434,6 @@ describe 'User', ->
expect(spell.lvl).to.be.above(0)
expect(spell.cast).to.be.a('function')
describe 'drop system', ->
user = null
@@ -481,6 +482,88 @@ describe 'User', ->
user.fns.randomVal.restore()
user.fns.predictableRandom.restore()
describe 'Enchanted Armoire', ->
user = newUser()
fullArmoire = {'weapon_warrior_0': true, 'armor_armoire_gladiatorArmor':true,'armor_armoire_lunarArmor':true,'head_armoire_gladiatorHelm':true,'head_armoire_lunarCrown':true,'head_armoire_rancherHat':true,'head_armoire_redHairbow':true,'head_armoire_violetFloppyHat':true,'shield_armoire_gladiatorShield':true,'weapon_armoire_basicCrossbow':true,'weapon_armoire_lunarSceptre':true}
beforeEach ->
# too many predictableRandom calls to stub, let's return the last element
sinon.stub(user.fns, 'randomVal', (obj)->
result = undefined
for key, val of obj
result = val
result
)
it 'counts all available equipment before any are claimed', ->
sinon.stub(user.fns, 'predictableRandom').returns 0
expect(shared.countArmoire(user.items.gear.owned)).to.eql (_.size(fullArmoire) - 1)
it 'does not open without paying', ->
sinon.stub(user.fns, 'predictableRandom').returns 0
user.ops.buy({params: {key: 'armoire'}})
expect(user.items.gear.owned).to.eql {'weapon_warrior_0': true}
expect(user.items.food).to.eql {}
expect(user.stats.exp).to.eql 0
it 'does not open without Ultimate Gear achievement', ->
sinon.stub(user.fns, 'predictableRandom').returns 0
user.stats.gp = 500
user.ops.buy({params: {key: 'armoire'}})
user.achievements.ultimateGearSets = {'healer':false,'wizard':false,'rogue':false,'warrior':false}
user.ops.buy({params: {key: 'armoire'}})
expect(user.items.gear.owned).to.eql {'weapon_warrior_0': true}
expect(user.items.food).to.eql {}
expect(user.stats.exp).to.eql 0
it 'always drops equipment the first time', ->
sinon.stub(user.fns, 'predictableRandom', cycle [.9,.5])
user.achievements.ultimateGearSets = {'healer':false,'wizard':false,'rogue':true,'warrior':false}
user.ops.buy({params: {key: 'armoire'}})
expect(user.items.gear.owned).to.eql {'weapon_warrior_0': true, 'shield_armoire_gladiatorShield':true}
expect(shared.countArmoire(user.items.gear.owned)).to.eql (_.size(fullArmoire) - 2)
expect(user.items.food).to.eql {}
expect(user.stats.exp).to.eql 0
expect(user.stats.gp).to.eql 400
it 'gives Experience', ->
sinon.stub(user.fns, 'predictableRandom', cycle [.9,.5])
user.ops.buy({params: {key: 'armoire'}})
expect(user.items.gear.owned).to.eql {'weapon_warrior_0': true, 'shield_armoire_gladiatorShield':true}
expect(user.items.food).to.eql {}
expect(user.stats.exp).to.eql 30
expect(user.stats.gp).to.eql 300
it 'gives food', ->
sinon.stub(user.fns, 'predictableRandom', cycle [.7,.5])
user.ops.buy({params: {key: 'armoire'}})
expect(user.items.gear.owned).to.eql {'weapon_warrior_0': true, 'shield_armoire_gladiatorShield':true}
expect(user.items.food).to.eql {'Honey': 1}
expect(user.stats.exp).to.eql 30
expect(user.stats.gp).to.eql 200
it 'gives more equipment', ->
sinon.stub(user.fns, 'predictableRandom', cycle [.5,.5])
user.ops.buy({params: {key: 'armoire'}})
expect(user.items.gear.owned).to.eql {'weapon_warrior_0': true, 'shield_armoire_gladiatorShield':true,'head_armoire_rancherHat':true}
expect(shared.countArmoire(user.items.gear.owned)).to.eql (_.size(fullArmoire) - 3)
expect(user.items.food).to.eql {'Honey': 1}
expect(user.stats.exp).to.eql 30
expect(user.stats.gp).to.eql 100
it 'does not give equipment if all equipment has been found', ->
sinon.stub(user.fns, 'predictableRandom', cycle [.5,.5])
user.items.gear.owned = fullArmoire
user.ops.buy({params: {key: 'armoire'}})
expect(user.items.gear.owned).to.eql fullArmoire
expect(shared.countArmoire(user.items.gear.owned)).to.eql 0
expect(user.items.food).to.eql {'Honey': 1}
expect(user.stats.exp).to.eql 60
expect(user.stats.gp).to.eql 0
afterEach ->
user.fns.randomVal.restore()
user.fns.predictableRandom.restore()
describe 'Quests', ->
_.each shared.content.quests, (quest)->
@@ -510,11 +593,19 @@ describe 'User', ->
_.each [1..5], (i) ->
user.ops.buy {params:'#{type}_#{klass}_#{i}'}
it 'does not get ultimateGear ' + klass, ->
expect(user.achievements.ultimateGear).to.not.be.ok()
expect(user.achievements.ultimateGearSets[klass]).to.not.be.ok()
_.each shared.content.gearTypes, (type) ->
user.ops.buy {params:'#{type}_#{klass}_6'}
xit 'gets ultimateGear ' + klass, ->
expect(user.achievements.ultimateGear).to.be.ok()
expect(user.achievements.ultimateGearSets[klass]).to.be.ok()
it 'does not remove existing Ultimate Gear achievements', ->
user = newUser()
user.achievements.ultimateGearSets = {'healer':true,'wizard':true,'rogue':true,'warrior':true}
user.items.gear.owned.shield_warrior_5 = false
user.items.gear.owned.weapon_rogue_6 = false
user.ops.buy {params:'shield_warrior_5'}
expect(user.achievements.ultimateGearSets).to.eql {'healer':true,'wizard':true,'rogue':true,'warrior':true}
it 'does not get beastMaster if user has less than 90 drop pets', ->
user = newUser()
@@ -792,8 +883,9 @@ describe 'Cron', ->
before.dailys[0].repeat = after.dailys[0].repeat = options.repeat if options.repeat
before.dailys[0].streak = after.dailys[0].streak = 10
before.dailys[0].completed = after.dailys[0].completed = true if options.checked
before.dailys[0].startDate = after.dailys[0].startDate = moment().subtract(30, 'days')
if options.shouldDo
expect(shared.shouldDo(now, options.repeat, {timezoneOffset, dayStart:options.dayStart, now})).to.be.ok()
expect(shared.shouldDo(now.toDate(), after.dailys[0], {timezoneOffset, dayStart:options.dayStart, now})).to.be.ok()
after.fns.cron {now}
before.stats.mp=after.stats.mp #FIXME
switch options.expect
+330
View File
@@ -0,0 +1,330 @@
_ = require 'lodash'
expect = require 'expect.js'
sinon = require 'sinon'
moment = require 'moment'
shared = require '../../common/script/index.coffee'
shared.i18n.translations = require('../../website/src/i18n.js').translations
repeatWithoutLastWeekday = ()->
repeat = {su:1,m:1,t:1,w:1,th:1,f:1,s:1}
if shared.startOfWeek(moment().zone(0)).isoWeekday() == 1 # Monday
repeat.su = false
else
repeat.s = false
{repeat: repeat}
### Helper Functions ####
# @TODO: Refactor into helper file
newUser = (addTasks=true)->
buffs = {per:0, int:0, con:0, str:0, stealth: 0, streaks: false}
user =
auth:
timestamps: {}
stats: {str:1, con:1, per:1, int:1, mp: 32, class: 'warrior', buffs: buffs}
items:
lastDrop:
count: 0
hatchingPotions: {}
eggs: {}
food: {}
gear:
equipped: {}
costume: {}
party:
quest:
progress:
down: 0
preferences: {}
dailys: []
todos: []
rewards: []
flags: {}
achievements: {}
contributor:
level: 2
shared.wrap(user)
user.ops.reset(null, ->)
if addTasks
_.each ['habit', 'todo', 'daily'], (task)->
user.ops.addTask {body: {type: task, id: shared.uuid()}}
user
cron = (usr) ->
usr.lastCron = moment().subtract(1,'days')
usr.fns.cron()
describe 'daily/weekly that repeats everyday (default)', ->
user = null
daily = null
weekly = null
describe 'when startDate is in the future', ->
beforeEach ->
user = newUser()
user.dailys = [
shared.taskDefaults({type:'daily', startDate: moment().add(7, 'days'), frequency: 'daily'})
shared.taskDefaults({type:'daily', startDate: moment().add(7, 'days'), frequency: 'weekly', repeat: {su:1,m:1,t:1,w:1,th:1,f:1,s:1}})
]
daily = user.dailys[0]
weekly = user.dailys[1]
it 'does not damage user for not completing it', ->
cron(user)
expect(user.stats.hp).to.be 50
it 'does not change value on cron if daily is incomplete', ->
cron(user)
expect(daily.value).to.be 0
expect(weekly.value).to.be 0
it 'does not reset checklists if daily is not marked as complete', ->
checklist = [
{
'text' : '1',
'id' : 'checklist-one',
'completed' : true
},
{
'text' : '2',
'id' : 'checklist-two',
'completed' : true
},
{
'text' : '3',
'id' : 'checklist-three',
'completed' : false
}
]
daily.checklist = checklist
weekly.checklist = checklist
cron(user)
expect(daily.checklist[0].completed).to.be true
expect(daily.checklist[1].completed).to.be true
expect(daily.checklist[2].completed).to.be false
expect(weekly.checklist[0].completed).to.be true
expect(weekly.checklist[1].completed).to.be true
expect(weekly.checklist[2].completed).to.be false
it 'resets checklists if daily is marked as complete', ->
checklist = [
{
'text' : '1',
'id' : 'checklist-one',
'completed' : true
},
{
'text' : '2',
'id' : 'checklist-two',
'completed' : true
},
{
'text' : '3',
'id' : 'checklist-three',
'completed' : false
}
]
daily.checklist = checklist
weekly.checklist = checklist
daily.completed = true
weekly.completed = true
cron(user)
_.each daily.checklist, (box)->
expect(box.completed).to.be false
_.each weekly.checklist, (box)->
expect(box.completed).to.be false
it 'is due on startDate', ->
daily_due_today = shared.shouldDo moment(), daily
daily_due_on_start_date = shared.shouldDo moment().add(7, 'days'), daily
expect(daily_due_today).to.be false
expect(daily_due_on_start_date).to.be true
weekly_due_today = shared.shouldDo moment(), weekly
weekly_due_on_start_date = shared.shouldDo moment().add(7, 'days'), weekly
expect(weekly_due_today).to.be false
expect(weekly_due_on_start_date).to.be true
describe 'when startDate is in the past', ->
completeDaily = null
beforeEach ->
user = newUser()
user.dailys = [
shared.taskDefaults({type:'daily', startDate: moment().subtract(7, 'days'), frequency: 'daily'})
shared.taskDefaults({type:'daily', startDate: moment().subtract(7, 'days'), frequency: 'weekly'})
]
daily = user.dailys[0]
weekly = user.dailys[1]
it 'does damage user for not completing it', ->
cron(user)
expect(user.stats.hp).to.be.lessThan 50
it 'decreases value on cron if daily is incomplete', ->
cron(user)
expect(daily.value).to.be.lessThan 0
expect(weekly.value).to.be.lessThan 0
it 'resets checklists if daily is not marked as complete', ->
checklist = [
{
'text' : '1',
'id' : 'checklist-one',
'completed' : true
},
{
'text' : '2',
'id' : 'checklist-two',
'completed' : true
},
{
'text' : '3',
'id' : 'checklist-three',
'completed' : false
}
]
daily.checklist = checklist
weekly.checklist = checklist
cron(user)
_.each daily.checklist, (box)->
expect(box.completed).to.be false
_.each weekly.checklist, (box)->
expect(box.completed).to.be false
it 'resets checklists if daily is marked as complete', ->
checklist = [
{
'text' : '1',
'id' : 'checklist-one',
'completed' : true
},
{
'text' : '2',
'id' : 'checklist-two',
'completed' : true
},
{
'text' : '3',
'id' : 'checklist-three',
'completed' : false
}
]
daily.checklist = checklist
daily.completed = true
weekly.checklist = checklist
weekly.completed = true
cron(user)
_.each daily.checklist, (box)->
expect(box.completed).to.be false
_.each weekly.checklist, (box)->
expect(box.completed).to.be false
describe 'when startDate is today', ->
completeDaily = null
beforeEach ->
user = newUser()
user.dailys = [
# Must set start date to yesterday, because cron mock sets last cron to yesterday
shared.taskDefaults({type:'daily', startDate: moment().subtract(1, 'days'), frequency: 'daily'})
shared.taskDefaults({type:'daily', startDate: moment().subtract(1, 'days'), frequency: 'weekly'})
]
daily = user.dailys[0]
weekly = user.dailys[1]
it 'does damage user for not completing it', ->
cron(user)
expect(user.stats.hp).to.be.lessThan 50
it 'decreases value on cron if daily is incomplete', ->
cron(user)
expect(daily.value).to.be.lessThan 0
expect(weekly.value).to.be.lessThan 0
it 'resets checklists if daily is not marked as complete', ->
checklist = [
{
'text' : '1',
'id' : 'checklist-one',
'completed' : true
},
{
'text' : '2',
'id' : 'checklist-two',
'completed' : true
},
{
'text' : '3',
'id' : 'checklist-three',
'completed' : false
}
]
daily.checklist = checklist
weekly.checklist = checklist
cron(user)
_.each daily.checklist, (box)->
expect(box.completed).to.be false
_.each weekly.checklist, (box)->
expect(box.completed).to.be false
it 'resets checklists if daily is marked as complete', ->
checklist = [
{
'text' : '1',
'id' : 'checklist-one',
'completed' : true
},
{
'text' : '2',
'id' : 'checklist-two',
'completed' : true
},
{
'text' : '3',
'id' : 'checklist-three',
'completed' : false
}
]
daily.checklist = checklist
daily.completed = true
weekly.checklist = checklist
weekly.completed = true
cron(user)
_.each daily.checklist, (box)->
expect(box.completed).to.be false
_.each weekly.checklist, (box)->
expect(box.completed).to.be false
describe 'daily that repeats every x days', ->
user = null
daily = null
beforeEach ->
user = newUser()
user.dailys = [ shared.taskDefaults({type:'daily', startDate: moment(), frequency: 'daily'}) ]
daily = user.dailys[0]
_.times 11, (due) ->
it 'where x equals ' + due, ->
daily.everyX = due
_.times 30, (day) ->
isDue = shared.shouldDo moment().add(day, 'days'), daily
expect(isDue).to.be true if day % due == 0
expect(isDue).to.be false if day % due != 0
@@ -0,0 +1,74 @@
'use strict'
TEST_DB = process.env.DB_NAME = 'habitrpg_migration_test'
process.env.NODE_DB_URI = 'mongodb://localhost/' + TEST_DB
app = require('../../website/src/server')
sh = require('shelljs')
runMigration = ->
sh.exec 'node ./migrations/20150604_ultimateGearSets.js'
describe 'Backfill for granting ultimate gear sets achievement', ->
before (done) ->
sh.exec "mongo \"#{TEST_DB}\" --eval \"db.dropDatabase()\""
done()
context 'User without any purchased equipment', ->
before (done) ->
registerNewUser done, true
it 'does not update user', (done)->
user_gear = user.items.gear.owned
expect(user_gear.weapon_wizard_6).to.not.exist
expect(user.achievements.ultimateGearSets).to.not.exist
runMigration()
User.findById user._id, (err, _user) ->
user = _user
expect(user.achievements.ultimateGearSets).to.not.exist
done()
context 'User with all but one needed piece of equipment', ->
before (done) ->
registerNewUser ->
items = {
weapon_wizard_6: true
armor_wizard_5: true
}
User.findByIdAndUpdate user._id, {'items.gear.owned': items}, (err, _user) ->
user = _user
done()
, true
it 'does not update user', (done)->
runMigration()
User.findById user._id, (err, _user) ->
user = _user
expect(user.achievements.ultimateGearSets).to.not.exist
done()
context 'User with all necessary equipment', ->
before (done) ->
registerNewUser ->
items = {
weapon_wizard_6: true
armor_wizard_5: true
head_wizard_5: true
}
User.findByIdAndUpdate user._id, {'items.gear.owned': items}, (err, _user) ->
user = _user
done()
, true
it 'grants user ultimate gear', (done)->
runMigration()
User.findById user._id, (err, _user) ->
user = _user
expect(user.achievements.ultimateGearSets.wizard).to.exist
done()
-99
View File
@@ -1,99 +0,0 @@
sh = require('shelljs')
async = require('async')
TEST_DB = 'habitrpg_test'
TEST_DB_URI = "mongodb://localhost/#{TEST_DB}"
TEST_SERVER_PORT = 3001
MAX_WAIT = 60
announce = (msg) ->
sh.echo '\x1b[36m%s\x1b[0m', "TEST SUITE: #{msg}"
Suite =
# Primary Task
run: ->
announce "Preparing the test environment."
Suite.prepareEnvironment ->
announce "Test prep complete. Waiting for server availability."
Suite.awaitServers ->
announce "Servers are ready. Beginning tests."
Suite.summarize
"API Specs": Suite.runApiSpecs()
"Common Specs": Suite.runCommonSpecs()
"End-to-End Specs": Suite.runE2ESpecs()
"Karma Specs": Suite.runKarmaSpecs()
# Output summary report when tests are done.
summarize: (results) ->
anyFailed = 0
sh.echo ""
announce "Tests complete!\n\nSummary\n-------\n"
for name, result of results
if result is 0
sh.echo '\x1b[36m%s\x1b[0m', "#{name}: \x1b[32mpassing"
else
anyFailed = 1
sh.echo '\x1b[36m%s\x1b[0m', "#{name}: \x1b[31mfailing"
sh.echo ""
announce "Thanks for helping keep Habitica clean!"
process.exit(anyFailed)
# Prepare files, db, and spin up servers.
prepareEnvironment: (cb) ->
sh.exec "grunt build:test"
sh.exec "mongo \"#{TEST_DB}\" --eval \"db.dropDatabase()\""
sh.exec "./node_modules/protractor/bin/webdriver-manager update"
# Spin this up even if we're not in a headless environment. Shouldn't matter.
sh.exec "Xvfb :99 -screen 0 1024x768x24 -extension RANDR", silent: true, async: true
sh.exec "./node_modules/protractor/bin/webdriver-manager start", silent: true, async: true
sh.exec "NODE_DB_URI=\"#{TEST_DB_URI}\" PORT=\"#{TEST_SERVER_PORT}\" node ./website/src/server.js", silent: true, async: true
cb()
# Ensure both the selenium and node servers are available
awaitServers: (cb) ->
async.parallel [Suite.awaitSelenium, Suite.awaitNode], (err, results) ->
throw err if err?
cb()
awaitSelenium: (cb) ->
waited = 0
interval = setInterval ->
if sh.exec('nc -z localhost 4444').code is 0
clearInterval(interval)
cb()
waited += 1
if waited > MAX_WAIT
clearInterval(interval)
cb(new Error("Timed out waiting for Selenium"))
, 1000
awaitNode: (cb) ->
waited = 0
interval = setInterval ->
if sh.exec('nc -z localhost 3001').code is 0
clearInterval(interval)
cb()
waited += 1
if waited > MAX_WAIT
clearInterval(interval)
cb(new Error("Timed out waiting for Node server"))
, 1000
runApiSpecs: ->
announce "Running API Specs (Mocha)"
sh.exec("NODE_ENV=testing ./node_modules/mocha/bin/mocha test/api").code
runCommonSpecs: ->
announce "Running Common Specs (Mocha)"
sh.exec("NODE_ENV=testing ./node_modules/mocha/bin/mocha test/common").code
runE2ESpecs: ->
announce "Running End-to-End Specs (Protractor)"
sh.exec("DISPLAY=:99 NODE_ENV=testing ./node_modules/protractor/bin/protractor protractor.conf.js").code
runKarmaSpecs: ->
announce "Running Karma Specs"
sh.exec("NODE_ENV=testing grunt karma:continuous").code
Suite.run()
+36
View File
@@ -0,0 +1,36 @@
'use strict';
describe('AppJS', function() {
describe('Automatic page refresh', function(){
var clock;
beforeEach(function () {
clock = sinon.useFakeTimers();
sinon.stub(window, "refresher", function(){return true});
});
afterEach(function () {
clock.restore();
window.refresher.restore();
});
it('should not call refresher if idle time is less than 6 hours', function() {
window.awaitIdle();
clock.tick(21599999);
expect(window.refresher).to.not.be.called;
});
it('should not call refresher if awaitIdle is called within 6 hours', function() {
window.awaitIdle();
clock.tick(21500000);
window.awaitIdle();
clock.tick(21500000);
expect(window.refresher).to.not.be.called;
});
it('should call refresher if idle time is 6 hours or greater', function() {
window.awaitIdle();
clock.tick(21600000);
expect(window.refresher).to.be.called;
});
});
});
+177
View File
@@ -0,0 +1,177 @@
'use strict';
describe('Challenges Controller', function() {
var $rootScope, scope, user, ctrl, challenges, groups;
beforeEach(function() {
module(function($provide) {
$provide.value('User', {});
});
inject(function($rootScope, $controller, Challenges, Groups){
user = specHelper.newUser();
user._id = "unique-user-id";
scope = $rootScope.$new();
// Load RootCtrl to ensure shared behaviors are loaded
$controller('RootCtrl', {$scope: scope, User: {user: user}});
ctrl = $controller('ChallengesCtrl', {$scope: scope, User: {user: user}});
challenges = Challenges;
groups = Groups;
});
});
describe('filterChallenges', function() {
var ownMem, ownNotMem, notOwnMem, notOwnNotMem;
beforeEach(function() {
ownMem = new challenges.Challenge({
name: 'test',
description: 'You are the owner and member',
habits: [],
dailys: [],
todos: [],
rewards: [],
leader: user._id,
group: "test",
timestamp: +(new Date),
members: [user],
official: false,
_isMember: true
});
ownNotMem = new challenges.Challenge({
name: 'test',
description: 'You are the owner, but not a member',
habits: [],
dailys: [],
todos: [],
rewards: [],
leader: user._id,
group: "test",
timestamp: +(new Date),
members: [],
official: false,
_isMember: false
});
notOwnMem = new challenges.Challenge({
name: 'test',
description: 'Not owner but a member',
habits: [],
dailys: [],
todos: [],
rewards: [],
leader: {_id:"test"},
group: "test",
timestamp: +(new Date),
members: [user],
official: false,
_isMember: true
});
notOwnNotMem = new challenges.Challenge({
name: 'test',
description: 'Not owner or member',
habits: [],
dailys: [],
todos: [],
rewards: [],
leader: {_id:"test"},
group: "test",
timestamp: +(new Date),
members: [],
official: false,
_isMember: false
});
scope.search = {
group: _.transform(groups, function(m,g){m[g._id]=true;})
};
});
it('displays challenges that match membership: either and owner: either', function() {
scope.search._isMember = 'either';
scope.search._isOwner = 'either';
expect(scope.filterChallenges(ownMem)).to.eql(true);
expect(scope.filterChallenges(ownNotMem)).to.eql(true);
expect(scope.filterChallenges(notOwnMem)).to.eql(true);
expect(scope.filterChallenges(notOwnNotMem)).to.eql(true);
});
it('displays challenges that match membership: either and owner: true', function() {
scope.search._isMember = 'either';
scope.search._isOwner = true;
expect(scope.filterChallenges(ownMem)).to.eql(true);
expect(scope.filterChallenges(ownNotMem)).to.eql(true);
expect(scope.filterChallenges(notOwnMem)).to.eql(false);
expect(scope.filterChallenges(notOwnNotMem)).to.eql(false);
});
it('displays challenges that match membership: either and owner: false', function() {
scope.search._isMember = 'either';
scope.search._isOwner = false;
expect(scope.filterChallenges(ownMem)).to.eql(false);
expect(scope.filterChallenges(ownNotMem)).to.eql(false);
expect(scope.filterChallenges(notOwnMem)).to.eql(true);
expect(scope.filterChallenges(notOwnNotMem)).to.eql(true);
});
it('displays challenges that match membership: true and owner: either', function() {
scope.search._isMember = true;
scope.search._isOwner = 'either';
expect(scope.filterChallenges(ownMem)).to.eql(true);
expect(scope.filterChallenges(ownNotMem)).to.eql(false);
expect(scope.filterChallenges(notOwnMem)).to.eql(true);
expect(scope.filterChallenges(notOwnNotMem)).to.eql(false);
});
it('displays challenges that match membership: true and owner: true', function() {
scope.search._isMember = true;
scope.search._isOwner = true;
expect(scope.filterChallenges(ownMem)).to.eql(true);
expect(scope.filterChallenges(ownNotMem)).to.eql(false);
expect(scope.filterChallenges(notOwnMem)).to.eql(false);
expect(scope.filterChallenges(notOwnNotMem)).to.eql(false);
});
it('displays challenges that match membership: true and owner: false', function() {
scope.search._isMember = true;
scope.search._isOwner = false;
expect(scope.filterChallenges(ownMem)).to.eql(false);
expect(scope.filterChallenges(ownNotMem)).to.eql(false);
expect(scope.filterChallenges(notOwnMem)).to.eql(true);
expect(scope.filterChallenges(notOwnNotMem)).to.eql(false);
});
it('displays challenges that match membership: false and owner: either', function() {
scope.search._isMember = false;
scope.search._isOwner = 'either';
expect(scope.filterChallenges(ownMem)).to.eql(false);
expect(scope.filterChallenges(ownNotMem)).to.eql(true);
expect(scope.filterChallenges(notOwnMem)).to.eql(false);
expect(scope.filterChallenges(notOwnNotMem)).to.eql(true);
});
it('displays challenges that match membership: false and owner: true', function() {
scope.search._isMember = false;
scope.search._isOwner = true;
expect(scope.filterChallenges(ownMem)).to.eql(false);
expect(scope.filterChallenges(ownNotMem)).to.eql(true);
expect(scope.filterChallenges(notOwnMem)).to.eql(false);
expect(scope.filterChallenges(notOwnNotMem)).to.eql(false);
});
it('displays challenges that match membership: false and owner: false', function() {
scope.search._isMember = false;
scope.search._isOwner = false;
expect(scope.filterChallenges(ownMem)).to.eql(false);
expect(scope.filterChallenges(ownNotMem)).to.eql(false);
expect(scope.filterChallenges(notOwnMem)).to.eql(false);
expect(scope.filterChallenges(notOwnNotMem)).to.eql(true);
});
});
});
+39
View File
@@ -0,0 +1,39 @@
'use strict';
describe('Filters Controller', function() {
var scope, user;
beforeEach(inject(function($rootScope, $controller, Shared) {
user = specHelper.newUser();
Shared.wrap(user);
scope = $rootScope.$new();
$controller('FiltersCtrl', {$scope: scope, User: {user: user}});
}));
describe('tags', function(){
it('creates a tag', function(){
scope._newTag = {name:'tagName'}
scope.createTag();
expect(user.tags).to.have.length(1);
expect(user.tags[0].name).to.eql('tagName');
expect(user.tags[0]).to.have.property('id');
});
it('toggles tag filtering', inject(function(Shared){
var tag = {id: Shared.uuid(), name: 'myTag'};
scope.toggleFilter(tag);
expect(user.filters[tag.id]).to.eql(true);
scope.toggleFilter(tag);
expect(user.filters[tag.id]).to.eql(false);
}));
});
describe('updateTaskFilter', function(){
it('updatest user\'s filter query with the value of filterQuery', function () {
scope.filterQuery = 'task';
scope.updateTaskFilter();
expect(user.filterQuery).to.eql(scope.filterQuery);
});
});
});
+56
View File
@@ -0,0 +1,56 @@
'use strict';
describe('Header Controller', function() {
var scope, ctrl, user, $location, $rootScope;
beforeEach(function() {
module(function($provide) {
$provide.value('User', {});
});
inject(function(_$rootScope_, _$controller_, _$location_){
user = specHelper.newUser();
user._id = "unique-user-id"
scope = _$rootScope_.$new();
$rootScope = _$rootScope_;
$location = _$location_;
// Load RootCtrl to ensure shared behaviors are loaded
_$controller_('RootCtrl', {$scope: scope, User: {user: user}});
ctrl = _$controller_('HeaderCtrl', {$scope: scope, User: {user: user}});
});
});
context('inviteOrStartParty', function(){
beforeEach(function(){
sinon.stub($location, 'path');
sinon.stub($rootScope, 'openModal');
});
afterEach(function(){
$location.path.restore();
$rootScope.openModal.restore();
});
it('redirects to party page if user does not have a party', function(){
var group = {};
scope.inviteOrStartParty(group);
expect($location.path).to.be.calledWith("/options/groups/party");
expect($rootScope.openModal).to.not.be.called;
});
it('Opens invite-friends modal if user has a party', function(){
var group = {
type: 'party'
};
scope.inviteOrStartParty(group);
expect($rootScope.openModal).to.be.calledOnce;
expect($location.path).to.not.be.called;
});
});
});
@@ -10,8 +10,12 @@ describe('Inventory Controller', function() {
inject(function($rootScope, $controller, Shared){
user = specHelper.newUser();
user.balance = 4,
user.items = {eggs: {Cactus: 1}, hatchingPotions: {Base: 1}, food: {Meat: 1}, pets: {}, mounts: {}};
user.balance = 4;
user.items.eggs = {Cactus: 1};
user.items.hatchingPotions = {Base: 1};
user.items.food = {Meat: 1};
user.items.pets = {}
user.items.mounts = {};
Shared.wrap(user);
var mockWindow = {
confirm: function(msg){
+194
View File
@@ -0,0 +1,194 @@
'use strict';
describe('Root Controller', function() {
var scope, rootscope, user, User, notification, ctrl, $httpBackend;
beforeEach(function () {
module(function($provide) {
$provide.value('User', {});
$provide.service('$templateCache', function () {
return {
get: function () {},
put: function () {}
}
});
});
inject(function($rootScope, $controller, _$httpBackend_, Notification) {
scope = $rootScope.$new();
scope.loginUsername = 'user';
scope.loginPassword = 'pass';
rootscope = $rootScope;
$httpBackend = _$httpBackend_;
notification = Notification;
sinon.stub(notification, 'text');
sinon.stub(notification, 'markdown');
user = specHelper.newUser();
User = {user: user};
User.save = sinon.spy();
User.sync = sinon.spy();
$httpBackend.whenGET(/partials/).respond();
ctrl = $controller('RootCtrl', {$scope: scope, User: User});
});
});
afterEach(function() {
notification.text.reset();
notification.markdown.reset();
User.save.reset();
User.sync.reset();
});
describe('contribText', function(){
it('shows contributor level text', function(){
expect(scope.contribText()).to.eql(undefined);
expect(scope.contribText(null, {npc: 'NPC'})).to.eql('NPC');
expect(scope.contribText({level: 0, text: 'Blacksmith'})).to.eql(undefined);
expect(scope.contribText({level: 1, text: 'Blacksmith'})).to.eql('Friend Blacksmith');
expect(scope.contribText({level: 2, text: 'Blacksmith'})).to.eql('Friend Blacksmith');
expect(scope.contribText({level: 3, text: 'Blacksmith'})).to.eql('Elite Blacksmith');
expect(scope.contribText({level: 4, text: 'Blacksmith'})).to.eql('Elite Blacksmith');
expect(scope.contribText({level: 5, text: 'Blacksmith'})).to.eql('Champion Blacksmith');
expect(scope.contribText({level: 6, text: 'Blacksmith'})).to.eql('Champion Blacksmith');
expect(scope.contribText({level: 7, text: 'Blacksmith'})).to.eql('Legendary Blacksmith');
expect(scope.contribText({level: 8, text: 'Blacksmith'})).to.eql('Guardian Blacksmith');
expect(scope.contribText({level: 9, text: 'Blacksmith'})).to.eql('Heroic Blacksmith');
expect(scope.contribText({level: 9, text: 'Blacksmith'}, {npc: 'NPC'})).to.eql('NPC');
});
});
describe('castEnd', function(){
var task_target, type;
beforeEach(function(){
task_target = {
id: 'task-id',
text: 'task'
};
type = 'task';
scope.spell = {
target: 'task',
key: 'fireball',
mana: 10,
text: function() { return env.t('spellWizardFireballText') },
cast: function(){}
};
rootscope.applyingAction = true;
});
context('fails', function(){
it('exits early if there is no applying action', function(){
rootscope.applyingAction = null;
expect(scope.castEnd(task_target, type)).to.be.eql('No applying action');
});
it('sends notification if target is invalid', function(){
scope.spell.target = 'not_the_same_target';
scope.castEnd(task_target, type);
notification.text.should.have.been.calledWith(window.env.t('invalidTarget'));
});
});
context('succeeds', function(){
it('sets scope.spell and rootScope.applyingAction to falsy values', function(){
scope.castEnd(task_target, type);
expect(rootscope.applyingAction).to.eql(false);
expect(scope.spell).to.eql(null);
});
it('calls $scope.spell.cast', function(){
// Kind of a hack, would prefer to use sinon.spy,
// but scope.spell gets turned to null in scope.castEnd
var spellWasCast = false;
scope.spell.cast = function(){ spellWasCast = true };
scope.castEnd(task_target, type);
expect(spellWasCast).to.eql(true);
});
it('calls cast endpoint', function() {
$httpBackend.expectPOST(/cast/).respond(201);
scope.castEnd(task_target, type);
$httpBackend.flush();
});
it('sends notification that spell was cast on task', function() {
$httpBackend.expectPOST(/cast/).respond(201);
scope.castEnd(task_target, type);
$httpBackend.flush();
expect(notification.markdown).to.be.calledOnce;
expect(notification.markdown).to.be.calledWith('You cast Burst of Flames on task.');
expect(User.sync).to.be.calledOnce;
});
it('sends notification that spell was cast on user', function() {
var user_target = {
profile: { name: 'Lefnire' }
};
scope.spell = {
target: 'user',
key: 'snowball',
mana: 0,
text: function() { return env.t('spellSpecialSnowballAuraText') },
cast: function(){}
};
$httpBackend.expectPOST(/cast/).respond(201);
scope.castEnd(user_target, 'user');
$httpBackend.flush();
expect(notification.markdown).to.be.calledOnce;
expect(notification.markdown).to.be.calledWith('You cast Snowball on Lefnire.');
expect(User.sync).to.be.calledOnce;
});
it('sends notification that spell was cast on party', function() {
var party_target = {};
scope.spell = {
target: 'party',
key: 'healAll',
mana: 25,
text: function() { return env.t('spellHealerHealAllText') },
cast: function(){}
};
$httpBackend.expectPOST(/cast/).respond(201);
scope.castEnd(party_target, 'party');
$httpBackend.flush();
expect(notification.markdown).to.be.calledOnce;
expect(notification.markdown).to.be.calledWith('You cast Blessing for the party.');
expect(User.sync).to.be.calledOnce;
});
it('sends notification that spell was cast on self', function() {
var self_target = {};
scope.spell = {
target: 'self',
key: 'stealth',
mana: 45,
text: function() { return env.t('spellRogueStealthText') },
cast: function(){}
};
$httpBackend.expectPOST(/cast/).respond(201);
scope.castEnd(self_target, 'self');
$httpBackend.flush();
expect(notification.markdown).to.be.calledOnce;
expect(notification.markdown).to.be.calledWith('You cast Stealth.');
expect(User.sync).to.be.calledOnce;
});
});
});
});
@@ -0,0 +1,28 @@
'use strict';
describe('focusMe Directive', function() {
var element, scope;
beforeEach(module('habitrpg'));
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
element = "<input focus-me></input>";
element = $compile(element)(scope);
scope.$digest();
}));
it('focuses the element when appended to the DOM', function() {
inject(function($timeout) {
var focusSpy = sinon.spy();
element.appendTo(document.body);
element.on('focus', focusSpy);
$timeout.flush();
expect(focusSpy).to.have.been.called;
});
});
});
@@ -0,0 +1,89 @@
'use strict';
describe('fromNow Directive', function() {
var element, scope;
var fromNow = 'recently';
var diff = 0;
beforeEach(module('habitrpg'));
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
scope.message = {};
sinon.stub(window, 'moment').returns({
fromNow: function() { return fromNow },
diff: function() { return diff }
});
element = "<p from-now></p>";
element = $compile(element)(scope);
scope.$digest();
}));
afterEach(function() {
window.moment.restore();
});
it('sets the element text to the elapsed time', function() {
expect(element.text()).to.eql('recently');
});
describe('when the elapsed time is less than an hour', function() {
beforeEach(inject(function($compile) {
fromNow = 'recently';
diff = 0;
element = $compile('<p from-now></p>')(scope);
scope.$digest();
}));
it('updates the elapsed time every minute', inject(function($interval) {
fromNow = 'later';
expect(element.text()).to.eql('recently');
$interval.flush(60001);
expect(element.text()).to.eql('later');
}));
it('moves to hourly updates after an hour', inject(function($timeout, $interval) {
diff = 61;
$timeout.flush();
$interval.flush(60001);
fromNow = 'later';
$interval.flush(60001);
expect(element.text()).to.eql('recently');
$interval.flush(3600000);
expect(element.text()).to.eql('later');
}));
});
describe('when the elapsed time is more than an hour', function() {
beforeEach(inject(function($compile) {
fromNow = 'recently';
diff = 65;
element = $compile('<p from-now></p>')(scope);
scope.$digest();
}));
it('updates the elapsed time every hour', inject(function($interval) {
fromNow = 'later';
expect(element.text()).to.eql('recently');
$interval.flush(60001);
expect(element.text()).to.eql('recently');
$interval.flush(3600000);
expect(element.text()).to.eql('later');
}));
});
});
@@ -0,0 +1,33 @@
describe('roundLargeNumbers', function() {
beforeEach(module('habitrpg'));
it('returns same number if less than 1000', inject(function(roundLargeNumbersFilter) {
for(var num = 0; num < 1000; num++) {
expect(roundLargeNumbersFilter(num)).to.eql(num);
};
}));
it('truncates number and appends "k" if number is 1000-999999', inject(function(roundLargeNumbersFilter) {
expect(roundLargeNumbersFilter(999.01)).to.eql("1.0k");
expect(roundLargeNumbersFilter(1000)).to.eql("1.0k");
expect(roundLargeNumbersFilter(3284.12)).to.eql("3.3k");
expect(roundLargeNumbersFilter(52983.99)).to.eql("53.0k");
expect(roundLargeNumbersFilter(452983.99)).to.eql("453.0k");
expect(roundLargeNumbersFilter(999999)).to.eql("1000.0k");
}));
it('truncates number and appends "m" if number is 1000000-999999999', inject(function(roundLargeNumbersFilter) {
expect(roundLargeNumbersFilter(999999.01)).to.eql("1.0m");
expect(roundLargeNumbersFilter(1000000)).to.eql("1.0m");
expect(roundLargeNumbersFilter(3284124.12)).to.eql("3.3m");
expect(roundLargeNumbersFilter(52983105.99)).to.eql("53.0m");
expect(roundLargeNumbersFilter(452983410.99)).to.eql("453.0m");
expect(roundLargeNumbersFilter(999999999)).to.eql("1000.0m");
}));
it('truncates number and appends b" if number is greater than 999999999', inject(function(roundLargeNumbersFilter) {
expect(roundLargeNumbersFilter(999999999.01)).to.eql("1.0b");
expect(roundLargeNumbersFilter(1423985738.54)).to.eql("1.4b");
}));
});
+35
View File
@@ -0,0 +1,35 @@
describe('filter', function() {
beforeEach(module('habitrpg'));
describe('gold', function() {
it('rounds down decimal values', inject(function(goldFilter) {
expect(goldFilter(10)).to.eql(10);
expect(goldFilter(10.0)).to.eql(10);
expect(goldFilter(10.1)).to.eql(10);
expect(goldFilter(10.2)).to.eql(10);
expect(goldFilter(10.3)).to.eql(10);
expect(goldFilter(10.4)).to.eql(10);
expect(goldFilter(10.5)).to.eql(10);
expect(goldFilter(10.6)).to.eql(10);
expect(goldFilter(10.7)).to.eql(10);
expect(goldFilter(10.8)).to.eql(10);
expect(goldFilter(10.9)).to.eql(10);
expect(goldFilter(11)).to.eql(11);
}));
});
describe('silver', function() {
it('converts decimal value of gold to silver', inject(function(silverFilter) {
expect(silverFilter(10)).to.be.closeTo(0, 1);
expect(silverFilter(10.01)).to.be.closeTo(1, 1);
expect(silverFilter(10.05)).to.be.closeTo(5, 1);
expect(silverFilter(10.17)).to.be.closeTo(17, 1);
expect(silverFilter(10.23)).to.be.closeTo(23, 1);
expect(silverFilter(10.25)).to.be.closeTo(25, 1);
expect(silverFilter(10.53)).to.be.closeTo(53, 1);
expect(silverFilter(10.75)).to.be.closeTo(75, 1);
expect(silverFilter(10.99)).to.be.closeTo(99, 1);
}));
});
});
+54
View File
@@ -0,0 +1,54 @@
'use strict';
describe('Task Ordering Filters', function() {
var filter
, orderBySpy = sinon.spy();
beforeEach(function() {
module(function($provide) {
$provide.value('orderByFilter', orderBySpy);
});
inject(function($rootScope, $filter) {
filter = $filter;
});
});
describe('conditionalOrderBy', function() {
describe('when the predicate is true', function() {
it('delegates the arguments to the orderBy filter', function() {
filter('conditionalOrderBy')('array', true, 'sortPredicate', 'reverseOrder');
expect(orderBySpy).to.have.been.calledWith('array','sortPredicate','reverseOrder');
});
});
describe('when the predicate is false', function() {
it('returns the initial array', function() {
expect(filter('conditionalOrderBy')([1,2,3], false)).to.eql([1,2,3]);
});
});
});
describe('filterByTextAndNotes', function () {
it('returns undefined when no input given', function () {
expect(filter('filterByTextAndNotes')()).to.eql(undefined);
});
it('returns input if term is not a string', function () {
var input = [1, 2, 3];
expect(filter('filterByTextAndNotes')(input, '')).to.eql(input);
expect(filter('filterByTextAndNotes')(input, undefined)).to.eql(input);
expect(filter('filterByTextAndNotes')(input, [])).to.eql(input);
expect(filter('filterByTextAndNotes')(input, new Date())).to.eql(input);
});
it('filters items by notes and text', function () {
var tasks = [
{ text: 'foo' },
{ text: 'foo', notes: 'bar' }
];
expect(filter('filterByTextAndNotes')(tasks, 'bar')).to.eql([tasks[1]]);
expect(filter('filterByTextAndNotes')(tasks, 'foo')).to.eql([tasks[0], tasks[1]]);
});
});
});
-28
View File
@@ -1,28 +0,0 @@
'use strict';
describe('Filters Controller', function() {
var scope, user;
beforeEach(inject(function($rootScope, $controller, Shared) {
user = specHelper.newUser();
Shared.wrap(user);
scope = $rootScope.$new();
$controller('FiltersCtrl', {$scope: scope, User: {user: user}});
}));
it('creates a tag', function(){
scope._newTag = {name:'tagName'}
scope.createTag();
expect(user.tags).to.have.length(1);
expect(user.tags[0].name).to.eql('tagName');
expect(user.tags[0]).to.have.property('id');
});
it('toggles tag filtering', inject(function(Shared){
var tag = {id: Shared.uuid(), name: 'myTag'};
scope.toggleFilter(tag);
expect(user.filters[tag.id]).to.eql(true);
scope.toggleFilter(tag);
expect(user.filters[tag.id]).to.eql(false);
}))
});
-30
View File
@@ -1,30 +0,0 @@
'use strict';
describe('Custom Filters', function() {
var filter
, orderBySpy = sinon.spy();
beforeEach(function() {
module(function($provide) {
$provide.value('orderByFilter', orderBySpy);
});
inject(function($rootScope, $filter) {
filter = $filter;
});
});
describe('conditionalOrderBy', function() {
describe('when the predicate is true', function() {
it('delegates the arguments to the orderBy filter', function() {
filter('conditionalOrderBy')('array', true, 'sortPredicate', 'reverseOrder');
expect(orderBySpy).to.have.been.calledWith('array','sortPredicate','reverseOrder');
});
});
describe('when the predicate is false', function() {
it('returns the initial array', function() {
expect(filter('conditionalOrderBy')([1,2,3], false)).to.eql([1,2,3]);
});
});
});
});
+30
View File
@@ -0,0 +1,30 @@
'use strict'
//Adapted from http://stackoverflow.com/questions/23785603/angularjs-testing-with-jasmine-and-mixpanel
// @TODO: replace with an injectable mixpanel instance for testing
var MixpanelMock;
MixpanelMock = (function() {
function MixpanelMock() {}
MixpanelMock.prototype.track = function() {
return console.log("mixpanel.track", arguments);
};
MixpanelMock.prototype.register_once = function() {
return console.log("mixpanel.register_once", arguments);
};
MixpanelMock.prototype.identify = function() {
return console.log("mixpanel.identify", arguments);
};
MixpanelMock.prototype.register = function() {
return console.log("mixpanel.register", arguments);
};
return MixpanelMock;
})();
window.mixpanel = new MixpanelMock();
-25
View File
@@ -1,25 +0,0 @@
'use strict';
//TODO mock bootstrapGrowl, add remaining tests
describe('notificationServices', function() {
var notification;
beforeEach(function() {
module(function($provide){
$provide.value('User', {});
});
inject(function(Notification) {
notification = Notification;
});
});
it('notifies coins amount', function() {
var SILVER_COIN = "<span class='notification-icon shop_silver'></span>";
var GOLD_COIN = "<span class='notification-icon shop_gold'></span>";
expect(notification.coins(0.01)).to.eql("1 " + SILVER_COIN);
expect(notification.coins(0.1)).to.eql("10 " + SILVER_COIN);
expect(notification.coins(1)).to.eql("1 " + GOLD_COIN);
expect(notification.coins(12.34)).to.eql("12 " + GOLD_COIN +" 33 " + SILVER_COIN);
});
});
-38
View File
@@ -1,38 +0,0 @@
'use strict';
// @TODO: Something here is calling a full page reload
describe('Root Controller', function() {
var scope, user, ctrl;
beforeEach(function () {
module(function($provide) {
$provide.value('User', {});
});
inject(function($rootScope, $controller) {
scope = $rootScope.$new();
scope.loginUsername = 'user'
scope.loginPassword = 'pass'
user = specHelper.newUser();
ctrl = $controller('RootCtrl', {$scope: scope, User: {user: user}});
});
});
it('shows contributor level text', function(){
expect(scope.contribText()).to.eql(undefined);
expect(scope.contribText(null, {npc: 'NPC'})).to.eql('NPC');
expect(scope.contribText({level: 0, text: 'Blacksmith'})).to.eql(undefined);
expect(scope.contribText({level: 1, text: 'Blacksmith'})).to.eql('Friend Blacksmith');
expect(scope.contribText({level: 2, text: 'Blacksmith'})).to.eql('Friend Blacksmith');
expect(scope.contribText({level: 3, text: 'Blacksmith'})).to.eql('Elite Blacksmith');
expect(scope.contribText({level: 4, text: 'Blacksmith'})).to.eql('Elite Blacksmith');
expect(scope.contribText({level: 5, text: 'Blacksmith'})).to.eql('Champion Blacksmith');
expect(scope.contribText({level: 6, text: 'Blacksmith'})).to.eql('Champion Blacksmith');
expect(scope.contribText({level: 7, text: 'Blacksmith'})).to.eql('Legendary Blacksmith');
expect(scope.contribText({level: 8, text: 'Blacksmith'})).to.eql('Guardian Blacksmith');
expect(scope.contribText({level: 9, text: 'Blacksmith'})).to.eql('Heroic Blacksmith');
expect(scope.contribText({level: 9, text: 'Blacksmith'}, {npc: 'NPC'})).to.eql('NPC');
});
});
@@ -0,0 +1,208 @@
'use strict';
describe('notificationServices', function() {
var notification;
before(function(){
sinon.stub($, 'pnotify', function(){
return { click: function(){}}
});
});
beforeEach(function() {
module(function($provide){
$provide.value('User', {});
});
inject(function(Notification) {
notification = Notification;
});
});
afterEach(function() {
$.pnotify.reset();
});
it('notifies coins amount', function() {
var SILVER_COIN = "<span class='notification-icon shop_silver'></span>";
var GOLD_COIN = "<span class='notification-icon shop_gold'></span>";
expect(notification.coins(0)).to.not.exist;
expect(notification.coins(0.01)).to.eql("1 " + SILVER_COIN);
expect(notification.coins(0.1)).to.eql("10 " + SILVER_COIN);
expect(notification.coins(1)).to.eql("1 " + GOLD_COIN);
expect(notification.coins(12.34)).to.eql("12 " + GOLD_COIN +" 33 " + SILVER_COIN);
});
it('sends crit notification', function() {
notification.crit(5);
var arg = $.pnotify.args[0][0];
expect($.pnotify).to.have.been.calledOnce;
expect(arg.type).to.eql('crit');
expect(arg.text).to.eql('Critical Hit! Bonus: 5%');
expect(arg.icon).to.eql('glyphicon glyphicon-certificate');
});
it('sends drop notification for unspecified item', function() {
notification.drop('msg');
var arg = $.pnotify.args[0][0];
expect($.pnotify).to.have.been.calledOnce;
expect(arg.type).to.eql('drop');
expect(arg.text).to.eql('msg');
expect(arg.icon).to.eql(false);
});
it('sends drop notification for Egg', function() {
var item = { type: 'Egg', key: 'wolf' };
notification.drop('msg', item);
var arg = $.pnotify.args[0][0];
expect($.pnotify).to.have.been.calledOnce;
expect(arg.type).to.eql('drop');
expect(arg.text).to.eql('msg');
expect(arg.icon).to.eql('Pet_Egg_wolf');
});
it('sends drop notification for Hatching Potion', function() {
var item = { type: 'HatchingPotion', key: 'red' };
notification.drop('msg', item);
var arg = $.pnotify.args[0][0];
expect($.pnotify).to.have.been.calledOnce;
expect(arg.type).to.eql('drop');
expect(arg.text).to.eql('msg');
expect(arg.icon).to.eql('Pet_HatchingPotion_red');
});
it('sends drop notification for Food', function() {
var item = { type: 'Food', key: 'meat' };
notification.drop('msg', item);
var arg = $.pnotify.args[0][0];
expect($.pnotify).to.have.been.calledOnce;
expect(arg.type).to.eql('drop');
expect(arg.text).to.eql('msg');
expect(arg.icon).to.eql('Pet_Food_meat');
});
it('does not send exp notification if val < -50', function() {
notification.exp(-51);
expect($.pnotify).to.not.have.been.called;
});
it('sends exp notification if val >= -50', function() {
notification.exp(50);
notification.exp(0);
notification.exp(-50);
var arg = $.pnotify.args[0][0];
expect($.pnotify).to.have.been.calledThrice;
expect(arg.type).to.eql('xp');
expect(arg.text).to.eql('+ 50 XP');
expect(arg.icon).to.eql('glyphicon glyphicon-star');
});
it('sends exp notification with rounded value', function() {
notification.exp(50.23333);
var arg = $.pnotify.args[0][0];
expect($.pnotify).to.have.been.calledOnce;
expect(arg.type).to.eql('xp');
expect(arg.text).to.eql('+ 50.2 XP');
expect(arg.icon).to.eql('glyphicon glyphicon-star');
});
it('sends error notification', function() {
notification.error('there was an error');
var arg = $.pnotify.args[0][0];
expect($.pnotify).to.have.been.calledOnce;
expect(arg.type).to.eql('danger');
expect(arg.text).to.eql('there was an error');
expect(arg.icon).to.eql('glyphicon glyphicon-exclamation-sign');
});
it('sends gp gained notification', function() {
notification.gp(50, 4);
var arg = $.pnotify.args[0][0];
expect($.pnotify).to.have.been.calledOnce;
expect(arg.type).to.eql('gp');
expect(arg.text).to.eql('+ 46 <span class=\'notification-icon shop_gold\'></span>');
expect(arg.icon).to.eql(false);
});
it('sends hp notification', function() {
notification.hp(10);
var arg = $.pnotify.args[0][0];
expect($.pnotify).to.have.been.calledOnce;
expect(arg.type).to.eql('hp');
expect(arg.text).to.eql('+ 10 HP');
expect(arg.icon).to.eql('glyphicon glyphicon-heart');
});
it('sends level up notification', function() {
notification.lvl(10);
var arg = $.pnotify.args[0][0];
expect($.pnotify).to.have.been.calledOnce;
expect(arg.type).to.eql('lvl');
expect(arg.text).to.eql('Level Up!');
expect(arg.icon).to.eql('glyphicon glyphicon-chevron-up');
});
it('sends markdown parsed notification', function() {
notification.markdown(":smile: - task name");
var arg = $.pnotify.args[0][0];
expect($.pnotify).to.have.been.calledOnce;
expect(arg.type).to.eql('info');
expect(arg.text).to.eql('<p><span class="emoji" style="background-image:url(common/img/emoji/unicode/1f604.png)">:smile:</span> - task name</p>\n');
expect(arg.icon).to.eql(false);
});
it('does not send markdown notification if no text is given', function() {
notification.markdown();
expect($.pnotify).to.not.have.been.called;
});
it('sends mp notification', function() {
notification.mp(10);
var arg = $.pnotify.args[0][0];
expect($.pnotify).to.have.been.calledOnce;
expect(arg.type).to.eql('mp');
expect(arg.text).to.eql('+ 10 MP');
expect(arg.icon).to.eql('glyphicon glyphicon-fire');
});
it('sends streak notification', function() {
notification.streak(10);
var arg = $.pnotify.args[0][0];
expect($.pnotify).to.have.been.calledOnce;
expect(arg.type).to.eql('streak');
expect(arg.text).to.eql('Streak Achievements: 10');
expect(arg.icon).to.eql('glyphicon glyphicon-repeat');
});
it('sends text notification', function() {
notification.text('task name');
var arg = $.pnotify.args[0][0];
expect($.pnotify).to.have.been.calledOnce;
expect(arg.type).to.eql('info');
expect(arg.text).to.eql('task name');
expect(arg.icon).to.eql(false);
});
it('does not send text notification if no text is given', function() {
notification.text();
expect($.pnotify).to.not.have.been.called;
});
});
+1 -1
View File
@@ -13,7 +13,7 @@ specHelper = {
food: {},
pets: {},
mounts: {},
gear: {equipped: {}, costume: {}},
gear: {equipped: {}, costume: {}, owned: {}},
},
party: {
quest: {