Merge branch 'master' into group-description

This commit is contained in:
nazoking
2017-01-15 03:39:14 +09:00
502 changed files with 42273 additions and 29949 deletions

View File

@@ -0,0 +1,79 @@
package gitbucket.core
import java.sql.DriverManager
import io.github.gitbucket.solidbase.Solidbase
import io.github.gitbucket.solidbase.model.Module
import liquibase.database.core.{H2Database, MySQLDatabase, PostgresDatabase}
import org.scalatest.{FunSuite, Tag}
import com.wix.mysql.EmbeddedMysql._
import com.wix.mysql.config.Charset
import com.wix.mysql.config.MysqldConfig._
import com.wix.mysql.distribution.Version._
import ru.yandex.qatools.embed.postgresql.PostgresStarter
import ru.yandex.qatools.embed.postgresql.config.AbstractPostgresConfig.{Credentials, Net, Storage, Timeout}
import ru.yandex.qatools.embed.postgresql.config.PostgresConfig
import ru.yandex.qatools.embed.postgresql.distribution.Version.Main.PRODUCTION
object ExternalDBTest extends Tag("ExternalDBTest")
class GitBucketCoreModuleSpec extends FunSuite {
test("Migration H2"){
new Solidbase().migrate(
DriverManager.getConnection("jdbc:h2:mem:test", "sa", "sa"),
Thread.currentThread().getContextClassLoader(),
new H2Database(),
new Module(GitBucketCoreModule.getModuleId, GitBucketCoreModule.getVersions)
)
}
test("Migration MySQL", ExternalDBTest){
val config = aMysqldConfig(v5_7_10)
.withPort(3306)
.withUser("sa", "sa")
.withCharset(Charset.UTF8)
.withServerVariable("log_syslog", 0)
.build()
val mysqld = anEmbeddedMysql(config)
.addSchema("gitbucket")
.start()
try {
new Solidbase().migrate(
DriverManager.getConnection("jdbc:mysql://localhost:3306/gitbucket?useSSL=false", "sa", "sa"),
Thread.currentThread().getContextClassLoader(),
new MySQLDatabase(),
new Module(GitBucketCoreModule.getModuleId, GitBucketCoreModule.getVersions)
)
} finally {
mysqld.stop()
}
}
test("Migration PostgreSQL", ExternalDBTest){
val runtime = PostgresStarter.getDefaultInstance()
val config = new PostgresConfig(
PRODUCTION,
new Net("localhost", 5432),
new Storage("gitbucket"),
new Timeout(),
new Credentials("sa", "sa"))
val exec = runtime.prepare(config)
val process = exec.start()
try {
new Solidbase().migrate(
DriverManager.getConnection("jdbc:postgresql://localhost:5432/gitbucket", "sa", "sa"),
Thread.currentThread().getContextClassLoader(),
new PostgresDatabase(),
new Module(GitBucketCoreModule.getModuleId, GitBucketCoreModule.getVersions)
)
} finally {
process.stop()
}
}
}

View File

@@ -2,31 +2,34 @@ package gitbucket.core.api
import gitbucket.core.util.RepositoryName
import org.specs2.mutable.Specification
import org.json4s.jackson.JsonMethods.{pretty, parse}
import org.json4s.jackson.JsonMethods.parse
import org.json4s._
import org.specs2.matcher._
import org.scalatest.FunSuite
import java.util.{Calendar, TimeZone}
import java.util.{Calendar, TimeZone, Date}
class JsonFormatSpec extends Specification {
class JsonFormatSpec extends FunSuite {
val date1 = {
val d = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
d.set(2011,3,14,16,0,49)
d.getTime
}
def date(date:String): Date = {
val f = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
f.setTimeZone(TimeZone.getTimeZone("UTC"))
f.parse(date)
}
val sha1 = "6dcb09b5b57875f334f61aebed695e2e4193db5e"
val repo1Name = RepositoryName("octocat/Hello-World")
implicit val context = JsonFormat.Context("http://gitbucket.exmple.com")
val apiUser = ApiUser(
login= "octocat",
email= "octocat@example.com",
`type`= "User",
site_admin= false,
created_at= date1)
login = "octocat",
email = "octocat@example.com",
`type` = "User",
site_admin = false,
created_at = date1)
val apiUserJson = """{
"login":"octocat",
"email":"octocat@example.com",
@@ -34,7 +37,8 @@ class JsonFormatSpec extends Specification {
"site_admin":false,
"created_at":"2011-04-14T16:00:49Z",
"url":"http://gitbucket.exmple.com/api/v3/users/octocat",
"html_url":"http://gitbucket.exmple.com/octocat"
"html_url":"http://gitbucket.exmple.com/octocat",
"avatar_url":"http://gitbucket.exmple.com/octocat/_avatar"
}"""
val repository = ApiRepository(
@@ -45,7 +49,7 @@ class JsonFormatSpec extends Specification {
forks = 0,
`private` = false,
default_branch = "master",
owner = apiUser)
owner = apiUser)(urlIsHtmlUrl = false)
val repositoryJson = s"""{
"name" : "Hello-World",
"full_name" : "octocat/Hello-World",
@@ -56,7 +60,7 @@ class JsonFormatSpec extends Specification {
"default_branch" : "master",
"owner" : $apiUserJson,
"forks_count" : 0,
"watchers_coun" : 0,
"watchers_count" : 0,
"url" : "${context.baseUrl}/api/v3/repos/octocat/Hello-World",
"http_url" : "${context.baseUrl}/git/octocat/Hello-World.git",
"clone_url" : "${context.baseUrl}/git/octocat/Hello-World.git",
@@ -85,12 +89,50 @@ class JsonFormatSpec extends Specification {
"url": "http://gitbucket.exmple.com/api/v3/repos/octocat/Hello-World/commits/6dcb09b5b57875f334f61aebed695e2e4193db5e/statuses"
}"""
val apiPushCommit = ApiCommit(
id = "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c",
message = "Update README.md",
timestamp = date1,
added = Nil,
removed = Nil,
modified = List("README.md"),
author = ApiPersonIdent("baxterthehacker","baxterthehacker@users.noreply.github.com",date1),
committer = ApiPersonIdent("baxterthehacker","baxterthehacker@users.noreply.github.com",date1))(RepositoryName("baxterthehacker", "public-repo"), true)
val apiPushCommitJson = s"""{
"id": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c",
// "distinct": true,
"message": "Update README.md",
"timestamp": "2011-04-14T16:00:49Z",
"url": "http://gitbucket.exmple.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c",
"author": {
"name": "baxterthehacker",
"email": "baxterthehacker@users.noreply.github.com",
// "username": "baxterthehacker",
"date" : "2011-04-14T16:00:49Z"
},
"committer": {
"name": "baxterthehacker",
"email": "baxterthehacker@users.noreply.github.com",
// "username": "baxterthehacker",
"date" : "2011-04-14T16:00:49Z"
},
"added": [
],
"removed": [
],
"modified": [
"README.md"
]
}"""
val apiComment = ApiComment(
id =1,
user = apiUser,
body= "Me too",
created_at= date1,
updated_at= date1)(RepositoryName("octocat","Hello-World"), 100)
updated_at= date1)(RepositoryName("octocat","Hello-World"), 100, false)
val apiCommentJson = s"""{
"id": 1,
"body": "Me too",
@@ -100,6 +142,21 @@ class JsonFormatSpec extends Specification {
"updated_at": "2011-04-14T16:00:49Z"
}"""
val apiCommentPR = ApiComment(
id =1,
user = apiUser,
body= "Me too",
created_at= date1,
updated_at= date1)(RepositoryName("octocat","Hello-World"), 100, true)
val apiCommentPRJson = s"""{
"id": 1,
"body": "Me too",
"user": $apiUserJson,
"html_url" : "${context.baseUrl}/octocat/Hello-World/pull/100#comment-1",
"created_at": "2011-04-14T16:00:49Z",
"updated_at": "2011-04-14T16:00:49Z"
}"""
val apiPersonIdent = ApiPersonIdent("Monalisa Octocat","support@example.com",date1)
val apiPersonIdentJson = """ {
"name": "Monalisa Octocat",
@@ -151,6 +208,15 @@ class JsonFormatSpec extends Specification {
"url": "${context.baseUrl}/api/v3/repos/octocat/Hello-World/commits/$sha1/status"
}"""
val apiLabel = ApiLabel(
name = "bug",
color = "f29513")(RepositoryName("octocat","Hello-World"))
val apiLabelJson = s"""{
"name": "bug",
"color": "f29513",
"url": "${context.baseUrl}/api/v3/repos/octocat/Hello-World/labels/bug"
}"""
val apiIssue = ApiIssue(
number = 1347,
title = "Found a bug",
@@ -158,7 +224,7 @@ class JsonFormatSpec extends Specification {
state = "open",
body = "I'm having a problem with this.",
created_at = date1,
updated_at = date1)(RepositoryName("octocat","Hello-World"))
updated_at = date1)(RepositoryName("octocat","Hello-World"), false)
val apiIssueJson = s"""{
"number": 1347,
"state": "open",
@@ -171,114 +237,204 @@ class JsonFormatSpec extends Specification {
"updated_at": "2011-04-14T16:00:49Z"
}"""
val apiPullRequest = ApiPullRequest(
number = 1347,
updated_at = date1,
val apiIssuePR = ApiIssue(
number = 1347,
title = "Found a bug",
user = apiUser,
state = "open",
body = "I'm having a problem with this.",
created_at = date1,
head = ApiPullRequest.Commit(
sha = sha1,
ref = "new-topic",
repo = repository)("octocat"),
base = ApiPullRequest.Commit(
sha = sha1,
ref = "master",
repo = repository)("octocat"),
mergeable = None,
title = "new-feature",
body = "Please pull these awesome changes",
user = apiUser
)
val apiPullRequestJson = s"""{
"url": "${context.baseUrl}/api/v3/repos/octocat/Hello-World/pulls/1347",
updated_at = date1)(RepositoryName("octocat","Hello-World"), true)
val apiIssuePRJson = s"""{
"number": 1347,
"state": "open",
"title": "Found a bug",
"body": "I'm having a problem with this.",
"user": $apiUserJson,
"comments_url": "${context.baseUrl}/api/v3/repos/octocat/Hello-World/issues/1347/comments",
"html_url": "${context.baseUrl}/octocat/Hello-World/pull/1347",
// "diff_url": "${context.baseUrl}/octocat/Hello-World/pull/1347.diff",
// "patch_url": "${context.baseUrl}/octocat/Hello-World/pull/1347.patch",
// "issue_url": "${context.baseUrl}/api/v3/repos/octocat/Hello-World/issues/1347",
"pull_request": {
"url": "${context.baseUrl}/api/v3/repos/octocat/Hello-World/pulls/1347",
"html_url": "${context.baseUrl}/octocat/Hello-World/pull/1347"
// "diff_url": "${context.baseUrl}/octocat/Hello-World/pull/1347.diff",
// "patch_url": "${context.baseUrl}/octocat/Hello-World/pull/1347.patch"
},
"created_at": "2011-04-14T16:00:49Z",
"updated_at": "2011-04-14T16:00:49Z"
}"""
val apiPullRequest = ApiPullRequest(
number = 1347,
updated_at = date1,
created_at = date1,
head = ApiPullRequest.Commit(
sha = sha1,
ref = "new-topic",
repo = repository)("octocat"),
base = ApiPullRequest.Commit(
sha = sha1,
ref = "master",
repo = repository)("octocat"),
mergeable = None,
merged = false,
merged_at = Some(date1),
merged_by = Some(apiUser),
title = "new-feature",
body = "Please pull these awesome changes",
user = apiUser
)
val apiPullRequestJson = s"""{
"number": 1347,
"updated_at": "2011-04-14T16:00:49Z",
"created_at": "2011-04-14T16:00:49Z",
// "closed_at": "2011-04-14T16:00:49Z",
"head": {
"sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e",
"ref": "new-topic",
"repo": $repositoryJson,
"label": "new-topic",
"user": $apiUserJson
},
"base": {
"sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e",
"ref": "master",
"repo": $repositoryJson,
"label": "master",
"user": $apiUserJson
},
// "merge_commit_sha": "e5bd3914e2e596debea16f433f57875b5b90bcd6",
// "mergeable": true,
"merged": false,
"merged_at": "2011-04-14T16:00:49Z",
"merged_by": $apiUserJson,
"title": "new-feature",
"body": "Please pull these awesome changes",
"user": $apiUserJson,
"html_url": "${context.baseUrl}/octocat/Hello-World/pull/1347",
"url": "${context.baseUrl}/api/v3/repos/octocat/Hello-World/pulls/1347",
"commits_url": "${context.baseUrl}/api/v3/repos/octocat/Hello-World/pulls/1347/commits",
"review_comments_url": "${context.baseUrl}/api/v3/repos/octocat/Hello-World/pulls/1347/comments",
"review_comment_url": "${context.baseUrl}/api/v3/repos/octocat/Hello-World/pulls/comments/{number}",
"comments_url": "${context.baseUrl}/api/v3/repos/octocat/Hello-World/issues/1347/comments",
"statuses_url": "${context.baseUrl}/api/v3/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e",
"number": 1347,
"statuses_url": "${context.baseUrl}/api/v3/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e"
// "diff_url": "${context.baseUrl}/octocat/Hello-World/pull/1347.diff",
// "patch_url": "${context.baseUrl}/octocat/Hello-World/pull/1347.patch",
// "issue_url": "${context.baseUrl}/api/v3/repos/octocat/Hello-World/issues/1347",
// "state": "open",
"title": "new-feature",
"body": "Please pull these awesome changes",
"created_at": "2011-04-14T16:00:49Z",
"updated_at": "2011-04-14T16:00:49Z",
// "closed_at": "2011-04-14T16:00:49Z",
// "merged_at": "2011-04-14T16:00:49Z",
"head": {
"label": "new-topic",
"ref": "new-topic",
"sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e",
"user": $apiUserJson,
"repo": $repositoryJson
},
"base": {
"label": "master",
"ref": "master",
"sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e",
"user": $apiUserJson,
"repo": $repositoryJson
},
"user": $apiUserJson
// "merge_commit_sha": "e5bd3914e2e596debea16f433f57875b5b90bcd6",
// "merged": false,
// "mergeable": true,
// "merged_by": $$apiUserJson,
// "comments": 10,
// "commits": 3,
// "additions": 100,
// "deletions": 3,
// "changed_files": 5
}"""
def beFormatted(json2Arg:String) = new Matcher[String] {
def apply[S <: String](e: Expectable[S]) = {
import java.util.regex.Pattern
val json2 = Pattern.compile("""^\s*//.*$""", Pattern.MULTILINE).matcher(json2Arg).replaceAll("")
val js2 = try{
parse(json2)
}catch{
case e:com.fasterxml.jackson.core.JsonParseException => {
val p = java.lang.Math.max(e.getLocation.getCharOffset()-10,0).toInt
val message = json2.substring(p,java.lang.Math.min(p+100,json2.length))
throw new com.fasterxml.jackson.core.JsonParseException(message + e.getMessage , e.getLocation)
}
// https://developer.github.com/v3/activity/events/types/#pullrequestreviewcommentevent
val apiPullRequestReviewComment = ApiPullRequestReviewComment(
id = 29724692,
// "diff_hunk": "@@ -1 +1 @@\n-# public-repo",
path = "README.md",
// "position": 1,
// "original_position": 1,
commit_id = "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c",
// "original_commit_id": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c",
user = apiUser,
body = "Maybe you should use more emojji on this line.",
created_at = date("2015-05-05T23:40:27Z"),
updated_at = date("2015-05-05T23:40:27Z")
)(RepositoryName("baxterthehacker/public-repo"), 1)
val apiPullRequestReviewCommentJson = s"""{
"url": "http://gitbucket.exmple.com/api/v3/repos/baxterthehacker/public-repo/pulls/comments/29724692",
"id": 29724692,
// "diff_hunk": "@@ -1 +1 @@\\n-# public-repo",
"path": "README.md",
// "position": 1,
// "original_position": 1,
"commit_id": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c",
// "original_commit_id": "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c",
"user": $apiUserJson,
"body": "Maybe you should use more emojji on this line.",
"created_at": "2015-05-05T23:40:27Z",
"updated_at": "2015-05-05T23:40:27Z",
"html_url": "http://gitbucket.exmple.com/baxterthehacker/public-repo/pull/1#discussion_r29724692",
"pull_request_url": "http://gitbucket.exmple.com/api/v3/repos/baxterthehacker/public-repo/pulls/1",
"_links": {
"self": {
"href": "http://gitbucket.exmple.com/api/v3/repos/baxterthehacker/public-repo/pulls/comments/29724692"
},
"html": {
"href": "http://gitbucket.exmple.com/baxterthehacker/public-repo/pull/1#discussion_r29724692"
},
"pull_request": {
"href": "http://gitbucket.exmple.com/api/v3/repos/baxterthehacker/public-repo/pulls/1"
}
val js1 = parse(e.value)
result(js1 == js2,
"expected",
{
val diff = js2 diff js1
s"${pretty(js1)} is not ${pretty(js2)} \n\n ${pretty(Extraction.decompose(diff)(org.json4s.DefaultFormats))}"
},
e)
}
}"""
val apiBranchProtection = ApiBranchProtection(true, Some(ApiBranchProtection.Status(ApiBranchProtection.Everyone, Seq("continuous-integration/travis-ci"))))
val apiBranchProtectionJson = """{
"enabled": true,
"required_status_checks": {
"enforcement_level": "everyone",
"contexts": [
"continuous-integration/travis-ci"
]
}
}"""
def assertJson(resultJson: String, expectJson: String) = {
import java.util.regex.Pattern
val json2 = Pattern.compile("""^\s*//.*$""", Pattern.MULTILINE).matcher(expectJson).replaceAll("")
val js2 = try {
parse(json2)
} catch {
case e: com.fasterxml.jackson.core.JsonParseException => {
val p = java.lang.Math.max(e.getLocation.getCharOffset() - 10, 0).toInt
val message = json2.substring(p, java.lang.Math.min(p + 100, json2.length))
throw new com.fasterxml.jackson.core.JsonParseException(message + e.getMessage, e.getLocation)
}
}
val js1 = parse(resultJson)
assert(js1 === js2)
}
"JsonFormat" should {
"apiUser" in {
JsonFormat(apiUser) must beFormatted(apiUserJson)
}
"repository" in {
JsonFormat(repository) must beFormatted(repositoryJson)
}
"apiComment" in {
JsonFormat(apiComment) must beFormatted(apiCommentJson)
}
"apiCommitListItem" in {
JsonFormat(apiCommitListItem) must beFormatted(apiCommitListItemJson)
}
"apiCommitStatus" in {
JsonFormat(apiCommitStatus) must beFormatted(apiCommitStatusJson)
}
"apiCombinedCommitStatus" in {
JsonFormat(apiCombinedCommitStatus) must beFormatted(apiCombinedCommitStatusJson)
}
"apiIssue" in {
JsonFormat(apiIssue) must beFormatted(apiIssueJson)
}
"apiPullRequest" in {
JsonFormat(apiPullRequest) must beFormatted(apiPullRequestJson)
}
test("apiUser") {
assertJson(JsonFormat(apiUser), apiUserJson)
}
test("repository") {
assertJson(JsonFormat(repository), repositoryJson)
}
test("apiPushCommit") {
assertJson(JsonFormat(apiPushCommit), apiPushCommitJson)
}
test("apiComment") {
assertJson(JsonFormat(apiComment), apiCommentJson)
assertJson(JsonFormat(apiCommentPR), apiCommentPRJson)
}
test("apiCommitListItem") {
assertJson(JsonFormat(apiCommitListItem), apiCommitListItemJson)
}
test("apiCommitStatus") {
assertJson(JsonFormat(apiCommitStatus), apiCommitStatusJson)
}
test("apiCombinedCommitStatus") {
assertJson(JsonFormat(apiCombinedCommitStatus), apiCombinedCommitStatusJson)
}
test("apiLabel") {
assertJson(JsonFormat(apiLabel), apiLabelJson)
}
test("apiIssue") {
assertJson(JsonFormat(apiIssue), apiIssueJson)
assertJson(JsonFormat(apiIssuePR), apiIssuePRJson)
}
test("apiPullRequest") {
assertJson(JsonFormat(apiPullRequest), apiPullRequestJson)
}
test("apiPullRequestReviewComment") {
assertJson(JsonFormat(apiPullRequestReviewComment), apiPullRequestReviewCommentJson)
}
test("apiBranchProtection") {
assertJson(JsonFormat(apiBranchProtection), apiBranchProtectionJson)
}
}

View File

@@ -1,26 +1,25 @@
package gitbucket.core.model
import gitbucket.core.model.CommitState._
import org.specs2.mutable.Specification
import org.scalatest.FunSpec
class CommitStateSpec extends Specification {
"CommitState" should {
"combine empty must eq PENDING" in {
combine(Set()) must_== PENDING
class CommitStateSpec extends FunSpec {
describe("CommitState") {
it("should combine empty must eq PENDING") {
assert(combine(Set()) == PENDING)
}
"combine includes ERROR must eq FAILURE" in {
combine(Set(ERROR, SUCCESS, PENDING)) must_== FAILURE
it("should combine includes ERROR must eq FAILURE") {
assert(combine(Set(ERROR, SUCCESS, PENDING)) == FAILURE)
}
"combine includes FAILURE must eq peinding" in {
combine(Set(FAILURE, SUCCESS, PENDING)) must_== FAILURE
it("should combine includes FAILURE must eq peinding") {
assert(combine(Set(FAILURE, SUCCESS, PENDING)) == FAILURE)
}
"combine includes PENDING must eq peinding" in {
combine(Set(PENDING, SUCCESS)) must_== PENDING
it("should combine includes PENDING must eq peinding") {
assert(combine(Set(PENDING, SUCCESS)) == PENDING)
}
"combine only SUCCESS must eq SUCCESS" in {
combine(Set(SUCCESS)) must_== SUCCESS
it("should combine only SUCCESS must eq SUCCESS") {
assert(combine(Set(SUCCESS)) == SUCCESS)
}
}
}

View File

@@ -1,91 +1,78 @@
package gitbucket.core.service
import gitbucket.core.model._
import org.specs2.mutable.Specification
import java.util.Date
import org.scalatest.FunSuite
class AccessTokenServiceSpec extends Specification with ServiceSpecBase {
class AccessTokenServiceSpec extends FunSuite with ServiceSpecBase {
"AccessTokenService" should {
"generateAccessToken" in { withTestDB { implicit session =>
AccessTokenService.generateAccessToken("root", "note") must be like{
case (id, token) if id != 0 => ok
}
}}
test("generateAccessToken") { withTestDB { implicit session =>
assert(AccessTokenService.generateAccessToken("root", "note") match {
case (id, token) => id != 0
})
}}
"getAccessTokens" in { withTestDB { implicit session =>
val (id, token) = AccessTokenService.generateAccessToken("root", "note")
val tokenHash = AccessTokenService.tokenToHash(token)
test("getAccessTokens") { withTestDB { implicit session =>
val (id, token) = AccessTokenService.generateAccessToken("root", "note")
val tokenHash = AccessTokenService.tokenToHash(token)
AccessTokenService.getAccessTokens("root") must be like{
case List(AccessToken(`id`, "root", `tokenHash`, "note")) => ok
}
}}
assert(AccessTokenService.getAccessTokens("root") == List(AccessToken(`id`, "root", `tokenHash`, "note")))
}}
"getAccessTokens(root) get root's tokens" in { withTestDB { implicit session =>
val (id, token) = AccessTokenService.generateAccessToken("root", "note")
val tokenHash = AccessTokenService.tokenToHash(token)
val user2 = generateNewAccount("user2")
AccessTokenService.generateAccessToken("user2", "note2")
test("getAccessTokens(root) get root's tokens") { withTestDB { implicit session =>
val (id, token) = AccessTokenService.generateAccessToken("root", "note")
val tokenHash = AccessTokenService.tokenToHash(token)
val user2 = generateNewAccount("user2")
AccessTokenService.generateAccessToken("user2", "note2")
AccessTokenService.getAccessTokens("root") must be like{
case List(AccessToken(`id`, "root", `tokenHash`, "note")) => ok
}
}}
assert(AccessTokenService.getAccessTokens("root") == List(AccessToken(`id`, "root", `tokenHash`, "note")))
}}
"deleteAccessToken" in { withTestDB { implicit session =>
val (id, token) = AccessTokenService.generateAccessToken("root", "note")
val user2 = generateNewAccount("user2")
AccessTokenService.generateAccessToken("user2", "note2")
test("deleteAccessToken") { withTestDB { implicit session =>
val (id, token) = AccessTokenService.generateAccessToken("root", "note")
val user2 = generateNewAccount("user2")
AccessTokenService.generateAccessToken("user2", "note2")
AccessTokenService.deleteAccessToken("root", id)
AccessTokenService.deleteAccessToken("root", id)
AccessTokenService.getAccessTokens("root") must beEmpty
}}
assert(AccessTokenService.getAccessTokens("root").isEmpty)
}}
"getAccountByAccessToken" in { withTestDB { implicit session =>
val (id, token) = AccessTokenService.generateAccessToken("root", "note")
AccessTokenService.getAccountByAccessToken(token) must beSome.like {
case user => user.userName must_== "root"
}
}}
test("getAccountByAccessToken") { withTestDB { implicit session =>
val (id, token) = AccessTokenService.generateAccessToken("root", "note")
assert(AccessTokenService.getAccountByAccessToken(token) match {
case Some(user) => user.userName == "root"
})
}}
"getAccountByAccessToken don't get removed account" in { withTestDB { implicit session =>
val user2 = generateNewAccount("user2")
val (id, token) = AccessTokenService.generateAccessToken("user2", "note")
AccountService.updateAccount(user2.copy(isRemoved=true))
test("getAccountByAccessToken don't get removed account") { withTestDB { implicit session =>
val user2 = generateNewAccount("user2")
val (id, token) = AccessTokenService.generateAccessToken("user2", "note")
AccountService.updateAccount(user2.copy(isRemoved=true))
AccessTokenService.getAccountByAccessToken(token) must beEmpty
}}
assert(AccessTokenService.getAccountByAccessToken(token).isEmpty)
}}
"generateAccessToken create uniq token" in { withTestDB { implicit session =>
val tokenIt = List("token1","token1","token1","token2").iterator
val service = new AccessTokenService{
override def makeAccessTokenString:String = tokenIt.next
}
test("generateAccessToken create uniq token") { withTestDB { implicit session =>
val tokenIt = List("token1","token1","token1","token2").iterator
val service = new AccessTokenService{
override def makeAccessTokenString:String = tokenIt.next
}
service.generateAccessToken("root", "note1") must like{
case (_, "token1") => ok
}
service.generateAccessToken("root", "note2") must like{
case (_, "token2") => ok
}
}}
assert(service.generateAccessToken("root", "note1")._2 == "token1")
assert(service.generateAccessToken("root", "note2")._2 == "token2")
}}
"when update Account.userName then AccessToken.userName changed" in { withTestDB { implicit session =>
val user2 = generateNewAccount("user2")
val (id, token) = AccessTokenService.generateAccessToken("user2", "note")
import gitbucket.core.model.Profile._
import profile.simple._
Accounts.filter(_.userName === "user2".bind).map(_.userName).update("user3")
test("when update Account.userName then AccessToken.userName changed") { withTestDB { implicit session =>
val user2 = generateNewAccount("user2")
val (id, token) = AccessTokenService.generateAccessToken("user2", "note")
import gitbucket.core.model.Profile._
import profile.simple._
Accounts.filter(_.userName === "user2".bind).map(_.userName).update("user3")
AccessTokenService.getAccountByAccessToken(token) must beSome.like {
case user => user.userName must_== "user3"
}
}}
}
assert(AccessTokenService.getAccountByAccessToken(token) match {
case Some(user) => user.userName == "user3"
})
}}
}

View File

@@ -1,102 +1,86 @@
package gitbucket.core.service
import gitbucket.core.model.{Account, GroupMember}
import org.specs2.mutable.Specification
import java.util.Date
import org.scalatest.FunSuite
class AccountServiceSpec extends Specification with ServiceSpecBase {
class AccountServiceSpec extends FunSuite with ServiceSpecBase {
"AccountService" should {
val RootMailAddress = "root@localhost"
val RootMailAddress = "root@localhost"
"getAllUsers" in { withTestDB { implicit session =>
AccountService.getAllUsers() must be like{
case List(Account("root", "root", RootMailAddress, _, true, _, _, _, None, None, false, false, None)) => ok
}
}}
test("getAllUsers") { withTestDB { implicit session =>
assert(AccountService.getAllUsers() match {
case List(Account("root", "root", RootMailAddress, _, true, _, _, _, None, None, false, false, None)) => true
case _ => false
})
}}
"getAccountByUserName" in { withTestDB { implicit session =>
AccountService.getAccountByUserName("root") must beSome.like {
case user => user.userName must_== "root"
}
test("getAccountByUserName") { withTestDB { implicit session =>
assert(AccountService.getAccountByUserName("root").get.userName == "root")
assert(AccountService.getAccountByUserName("invalid user name").isEmpty)
}}
AccountService.getAccountByUserName("invalid user name") must beNone
}}
test("getAccountByMailAddress") { withTestDB { implicit session =>
assert(AccountService.getAccountByMailAddress(RootMailAddress).isDefined)
}}
"getAccountByMailAddress" in { withTestDB { implicit session =>
AccountService.getAccountByMailAddress(RootMailAddress) must beSome
}}
test("updateLastLoginDate") { withTestDB { implicit session =>
val root = "root"
def user() = AccountService.getAccountByUserName(root).getOrElse(sys.error(s"user $root does not exists"))
"updateLastLoginDate" in { withTestDB { implicit session =>
val root = "root"
def user() =
AccountService.getAccountByUserName(root).getOrElse(sys.error(s"user $root does not exists"))
assert(user().lastLoginDate.isEmpty)
user().lastLoginDate must beNone
val date1 = new Date
AccountService.updateLastLoginDate(root)
user().lastLoginDate must beSome.like{ case date =>
date must be_>(date1)
}
val date2 = new Date
Thread.sleep(1000)
AccountService.updateLastLoginDate(root)
user().lastLoginDate must beSome.like{ case date =>
date must be_>(date2)
}
}}
val date1 = new Date
AccountService.updateLastLoginDate(root)
assert(user().lastLoginDate.get.compareTo(date1) > 0)
"updateAccount" in { withTestDB { implicit session =>
val root = "root"
def user() =
AccountService.getAccountByUserName(root).getOrElse(sys.error(s"user $root does not exists"))
val date2 = new Date
Thread.sleep(1000)
AccountService.updateLastLoginDate(root)
assert(user().lastLoginDate.get.compareTo(date2) > 0)
}}
val newAddress = "new mail address"
AccountService.updateAccount(user().copy(mailAddress = newAddress))
user().mailAddress must_== newAddress
}}
test("updateAccount") { withTestDB { implicit session =>
val root = "root"
def user() = AccountService.getAccountByUserName(root).getOrElse(sys.error(s"user $root does not exists"))
"group" in { withTestDB { implicit session =>
val group1 = "group1"
val user1 = "root"
AccountService.createGroup(group1, None, None)
val newAddress = "new mail address"
AccountService.updateAccount(user().copy(mailAddress = newAddress))
assert(user().mailAddress == newAddress)
}}
AccountService.getGroupMembers(group1) must_== Nil
AccountService.getGroupsByUserName(user1) must_== Nil
test("group") { withTestDB { implicit session =>
val group1 = "group1"
val user1 = "root"
AccountService.createGroup(group1, None, None)
AccountService.updateGroupMembers(group1, List((user1, true)))
assert(AccountService.getGroupMembers(group1) == Nil)
assert(AccountService.getGroupsByUserName(user1) == Nil)
AccountService.getGroupMembers(group1) must_== List(GroupMember(group1, user1, true))
AccountService.getGroupsByUserName(user1) must_== List(group1)
AccountService.updateGroupMembers(group1, List((user1, true)))
AccountService.updateGroupMembers(group1, Nil)
assert(AccountService.getGroupMembers(group1) == List(GroupMember(group1, user1, true)))
assert(AccountService.getGroupsByUserName(user1) == List(group1))
AccountService.getGroupMembers(group1) must_== Nil
AccountService.getGroupsByUserName(user1) must_== Nil
}}
AccountService.updateGroupMembers(group1, Nil)
"createGroup" should { withTestDB { implicit session =>
"save description" in {
AccountService.createGroup("some-group", None, Some("some clever description"))
val maybeGroup = AccountService.getAccountByUserName("some-group")
assert(AccountService.getGroupMembers(group1) == Nil)
assert(AccountService.getGroupsByUserName(user1) == Nil)
}}
maybeGroup must beSome.like {
case account => account.groupDescription must beSome("some clever description")
}
}
}}
test("createGroup save description") { withTestDB { implicit session =>
AccountService.createGroup("some-group", None, Some("some clever description"))
val maybeGroup = AccountService.getAccountByUserName("some-group")
"updateGroup" should { withTestDB { implicit session =>
"save description" in {
AccountService.createGroup("a-group", None, None)
assert(maybeGroup.flatMap(_.groupDescription) == Some("some clever description"))
}}
AccountService.updateGroup("a-group", None, Some("new description"), false)
test("updateGroup save description") { withTestDB { implicit session =>
AccountService.createGroup("a-group", None, None)
val group = AccountService.getAccountByUserName("a-group")
group must beSome.like {
case account => account.groupDescription must beSome("new description")
}
}
}}
}
AccountService.updateGroup("a-group", None, Some("new description"), false)
val group = AccountService.getAccountByUserName("a-group")
assert(group.flatMap(_.groupDescription) == Some("new description"))
}}
}

View File

@@ -1,78 +0,0 @@
package gitbucket.core.service
import gitbucket.core.model._
import gitbucket.core.model.Profile._
import profile.simple._
import org.specs2.mutable.Specification
import java.util.Date
class CommitStatusServiceSpec extends Specification with ServiceSpecBase with CommitStatusService
with RepositoryService with AccountService{
val now = new java.util.Date()
val fixture1 = CommitStatus(
userName = "root",
repositoryName = "repo",
commitId = "0e97b8f59f7cdd709418bb59de53f741fd1c1bd7",
context = "jenkins/test",
creator = "tester",
state = CommitState.PENDING,
targetUrl = Some("http://example.com/target"),
description = Some("description"),
updatedDate = now,
registeredDate = now)
def findById(id: Int)(implicit s:Session) = CommitStatuses.filter(_.byPrimaryKey(id)).firstOption
def generateFixture1(tester:Account)(implicit s:Session) = createCommitStatus(
userName = fixture1.userName,
repositoryName = fixture1.repositoryName,
sha = fixture1.commitId,
context = fixture1.context,
state = fixture1.state,
targetUrl = fixture1.targetUrl,
description = fixture1.description,
creator = tester,
now = fixture1.registeredDate)
"CommitStatusService" should {
"createCommitState can insert and update" in { withTestDB { implicit session =>
val tester = generateNewAccount(fixture1.creator)
createRepository(fixture1.repositoryName,fixture1.userName,None,false)
val id = generateFixture1(tester:Account)
getCommitStatus(fixture1.userName, fixture1.repositoryName, id) must_==
Some(fixture1.copy(commitStatusId=id))
// other one can update
val tester2 = generateNewAccount("tester2")
val time2 = new java.util.Date();
val id2 = createCommitStatus(
userName = fixture1.userName,
repositoryName = fixture1.repositoryName,
sha = fixture1.commitId,
context = fixture1.context,
state = CommitState.SUCCESS,
targetUrl = Some("http://example.com/target2"),
description = Some("description2"),
creator = tester2,
now = time2)
getCommitStatus(fixture1.userName, fixture1.repositoryName, id2) must_== Some(fixture1.copy(
commitStatusId = id,
creator = "tester2",
state = CommitState.SUCCESS,
targetUrl = Some("http://example.com/target2"),
description = Some("description2"),
updatedDate = time2))
}}
"getCommitStatus can find by commitId and context" in { withTestDB { implicit session =>
val tester = generateNewAccount(fixture1.creator)
createRepository(fixture1.repositoryName,fixture1.userName,None,false)
val id = generateFixture1(tester:Account)
getCommitStatus(fixture1.userName, fixture1.repositoryName, fixture1.commitId, fixture1.context) must_== Some(fixture1.copy(commitStatusId=id))
}}
"getCommitStatus can find by commitStatusId" in { withTestDB { implicit session =>
val tester = generateNewAccount(fixture1.creator)
createRepository(fixture1.repositoryName,fixture1.userName,None,false)
val id = generateFixture1(tester:Account)
getCommitStatus(fixture1.userName, fixture1.repositoryName, id) must_== Some(fixture1.copy(commitStatusId=id))
}}
}
}

View File

@@ -0,0 +1,74 @@
package gitbucket.core.service
import gitbucket.core.model._
import gitbucket.core.model.Profile._
import profile.simple._
import org.scalatest.FunSuite
class CommitStatusServiceSpec extends FunSuite with ServiceSpecBase with CommitStatusService
with RepositoryService with AccountService{
val now = new java.util.Date()
val fixture1 = CommitStatus(
userName = "root",
repositoryName = "repo",
commitId = "0e97b8f59f7cdd709418bb59de53f741fd1c1bd7",
context = "jenkins/test",
creator = "tester",
state = CommitState.PENDING,
targetUrl = Some("http://example.com/target"),
description = Some("description"),
updatedDate = now,
registeredDate = now)
def findById(id: Int)(implicit s:Session) = CommitStatuses.filter(_.byPrimaryKey(id)).firstOption
def generateFixture1(tester:Account)(implicit s:Session) = createCommitStatus(
userName = fixture1.userName,
repositoryName = fixture1.repositoryName,
sha = fixture1.commitId,
context = fixture1.context,
state = fixture1.state,
targetUrl = fixture1.targetUrl,
description = fixture1.description,
creator = tester,
now = fixture1.registeredDate)
test("createCommitState can insert and update") { withTestDB { implicit session =>
val tester = generateNewAccount(fixture1.creator)
insertRepository(fixture1.repositoryName,fixture1.userName,None,false)
val id = generateFixture1(tester:Account)
assert(getCommitStatus(fixture1.userName, fixture1.repositoryName, id) == Some(fixture1.copy(commitStatusId=id)))
// other one can update
val tester2 = generateNewAccount("tester2")
val time2 = new java.util.Date();
val id2 = createCommitStatus(
userName = fixture1.userName,
repositoryName = fixture1.repositoryName,
sha = fixture1.commitId,
context = fixture1.context,
state = CommitState.SUCCESS,
targetUrl = Some("http://example.com/target2"),
description = Some("description2"),
creator = tester2,
now = time2)
assert(getCommitStatus(fixture1.userName, fixture1.repositoryName, id2) == Some(fixture1.copy(
commitStatusId = id,
creator = "tester2",
state = CommitState.SUCCESS,
targetUrl = Some("http://example.com/target2"),
description = Some("description2"),
updatedDate = time2)))
}}
test("getCommitStatus can find by commitId and context") { withTestDB { implicit session =>
val tester = generateNewAccount(fixture1.creator)
insertRepository(fixture1.repositoryName,fixture1.userName,None,false)
val id = generateFixture1(tester:Account)
assert(getCommitStatus(fixture1.userName, fixture1.repositoryName, fixture1.commitId, fixture1.context) == Some(fixture1.copy(commitStatusId=id)))
}}
test("getCommitStatus can find by commitStatusId") { withTestDB { implicit session =>
val tester = generateNewAccount(fixture1.creator)
insertRepository(fixture1.repositoryName,fixture1.userName,None,false)
val id = generateFixture1(tester:Account)
assert(getCommitStatus(fixture1.userName, fixture1.repositoryName, id) == Some(fixture1.copy(commitStatusId=id)))
}}
}

View File

@@ -2,49 +2,44 @@ package gitbucket.core.service
import gitbucket.core.model._
import gitbucket.core.service.IssuesService._
import org.specs2.mutable.Specification
import java.util.Date
import org.scalatest.FunSuite
class IssuesServiceSpec extends Specification with ServiceSpecBase {
"IssuesService" should {
"getCommitStatues" in { withTestDB { implicit session =>
val user1 = generateNewUserWithDBRepository("user1","repo1")
class IssuesServiceSpec extends FunSuite with ServiceSpecBase {
test("getCommitStatues") { withTestDB { implicit session =>
val user1 = generateNewUserWithDBRepository("user1","repo1")
def getCommitStatues = dummyService.getCommitStatues(List(("user1","repo1",1),("user1","repo1",2)))
def getCommitStatues = dummyService.getCommitStatues(List(("user1","repo1",1),("user1","repo1",2)))
getCommitStatues must_== Map.empty
assert(getCommitStatues == Map.empty)
val now = new java.util.Date()
val issueId = generateNewIssue("user1","repo1")
issueId must_== 1
val now = new java.util.Date()
val issueId = generateNewIssue("user1","repo1")
assert(issueId == 1)
getCommitStatues must_== Map.empty
assert(getCommitStatues == Map.empty)
val cs = dummyService.createCommitStatus("user1","repo1","shasha", "default", CommitState.SUCCESS, Some("http://exmple.com/ci"), Some("exampleService"), now, user1)
val cs = dummyService.createCommitStatus("user1","repo1","shasha", "default", CommitState.SUCCESS, Some("http://exmple.com/ci"), Some("exampleService"), now, user1)
getCommitStatues must_== Map.empty
assert(getCommitStatues == Map.empty)
val (is2, pr2) = generateNewPullRequest("user1/repo1/master","user1/repo1/feature1")
pr2.issueId must_== 2
val (is2, pr2) = generateNewPullRequest("user1/repo1/master","user1/repo1/feature1")
assert(pr2.issueId == 2)
// if there are no statuses, state is none
getCommitStatues must_== Map.empty
// if there are no statuses, state is none
assert(getCommitStatues == Map.empty)
// if there is a status, state is that
val cs2 = dummyService.createCommitStatus("user1","repo1","feature1", "default", CommitState.SUCCESS, Some("http://exmple.com/ci"), Some("exampleService"), now, user1)
getCommitStatues must_== Map(("user1","repo1",2) -> CommitStatusInfo(1,1,Some("default"),Some(CommitState.SUCCESS),Some("http://exmple.com/ci"),Some("exampleService")))
// if there is a status, state is that
val cs2 = dummyService.createCommitStatus("user1","repo1","feature1", "default", CommitState.SUCCESS, Some("http://exmple.com/ci"), Some("exampleService"), now, user1)
assert(getCommitStatues == Map(("user1","repo1",2) -> CommitStatusInfo(1,1,Some("default"),Some(CommitState.SUCCESS),Some("http://exmple.com/ci"),Some("exampleService"))))
// if there are two statuses, state is none
val cs3 = dummyService.createCommitStatus("user1","repo1","feature1", "pend", CommitState.PENDING, Some("http://exmple.com/ci"), Some("exampleService"), now, user1)
getCommitStatues must_== Map(("user1","repo1",2) -> CommitStatusInfo(2,1,None,None,None,None))
// if there are two statuses, state is none
val cs3 = dummyService.createCommitStatus("user1","repo1","feature1", "pend", CommitState.PENDING, Some("http://exmple.com/ci"), Some("exampleService"), now, user1)
assert(getCommitStatues == Map(("user1","repo1",2) -> CommitStatusInfo(2,1,None,None,None,None)))
// get only statuses in query issues
val (is3, pr3) = generateNewPullRequest("user1/repo1/master","user1/repo1/feature3")
val cs4 = dummyService.createCommitStatus("user1","repo1","feature3", "none", CommitState.PENDING, None, None, now, user1)
getCommitStatues must_== Map(("user1","repo1",2) -> CommitStatusInfo(2,1,None,None,None,None))
} }
}
// get only statuses in query issues
val (is3, pr3) = generateNewPullRequest("user1/repo1/master","user1/repo1/feature3")
val cs4 = dummyService.createCommitStatus("user1","repo1","feature3", "none", CommitState.PENDING, None, None, now, user1)
assert(getCommitStatues == Map(("user1","repo1",2) -> CommitStatusInfo(2,1,None,None,None,None)))
} }
}

View File

@@ -0,0 +1,115 @@
package gitbucket.core.service
import gitbucket.core.model._
import org.scalatest.FunSpec
class LabelsServiceSpec extends FunSpec with ServiceSpecBase {
describe("getLabels") {
it("should be empty when not have any labels") { withTestDB { implicit session =>
generateNewUserWithDBRepository("user1", "repo1")
generateNewUserWithDBRepository("user1", "repo2")
dummyService.createLabel("user1", "repo2", "label1", "000000")
generateNewUserWithDBRepository("user2", "repo1")
dummyService.createLabel("user2", "repo1", "label1", "000000")
assert(dummyService.getLabels("user1", "repo1").isEmpty)
}}
it("should return contained labels") { withTestDB { implicit session =>
generateNewUserWithDBRepository("user1", "repo1")
val labelId1 = dummyService.createLabel("user1", "repo1", "label1", "000000")
val labelId2 = dummyService.createLabel("user1", "repo1", "label2", "ffffff")
generateNewUserWithDBRepository("user1", "repo2")
dummyService.createLabel("user1", "repo2", "label1", "000000")
generateNewUserWithDBRepository("user2", "repo1")
dummyService.createLabel("user2", "repo1", "label1", "000000")
def getLabels = dummyService.getLabels("user1", "repo1")
assert(getLabels.length == 2)
assert(getLabels == List(
Label("user1", "repo1", labelId1, "label1", "000000"),
Label("user1", "repo1", labelId2, "label2", "ffffff"))
)
}}
}
describe("getLabel") {
it("should return None when the label not exist") { withTestDB { implicit session =>
generateNewUserWithDBRepository("user1", "repo1")
assert(dummyService.getLabel("user1", "repo1", 1) == None)
assert(dummyService.getLabel("user1", "repo1", "label1") == None)
}}
it("should return a label fetched by label id") { withTestDB { implicit session =>
generateNewUserWithDBRepository("user1", "repo1")
val labelId1 = dummyService.createLabel("user1", "repo1", "label1", "000000")
dummyService.createLabel("user1", "repo1", "label2", "ffffff")
generateNewUserWithDBRepository("user1", "repo2")
dummyService.createLabel("user1", "repo2", "label1", "000000")
generateNewUserWithDBRepository("user2", "repo1")
dummyService.createLabel("user2", "repo1", "label1", "000000")
def getLabel = dummyService.getLabel("user1", "repo1", labelId1)
assert(getLabel == Some(Label("user1", "repo1", labelId1, "label1", "000000")))
}}
it("should return a label fetched by label name") { withTestDB { implicit session =>
generateNewUserWithDBRepository("user1", "repo1")
val labelId1 = dummyService.createLabel("user1", "repo1", "label1", "000000")
dummyService.createLabel("user1", "repo1", "label2", "ffffff")
generateNewUserWithDBRepository("user1", "repo2")
dummyService.createLabel("user1", "repo2", "label1", "000000")
generateNewUserWithDBRepository("user2", "repo1")
dummyService.createLabel("user2", "repo1", "label1", "000000")
def getLabel = dummyService.getLabel("user1", "repo1", "label1")
getLabel == Some(Label("user1", "repo1", labelId1, "label1", "000000"))
}}
}
describe("createLabel") {
it("should return accurate label id") { withTestDB { implicit session =>
generateNewUserWithDBRepository("user1", "repo1")
generateNewUserWithDBRepository("user1", "repo2")
generateNewUserWithDBRepository("user2", "repo1")
dummyService.createLabel("user1", "repo1", "label1", "000000")
dummyService.createLabel("user1", "repo2", "label1", "000000")
dummyService.createLabel("user2", "repo1", "label1", "000000")
val labelId = dummyService.createLabel("user1", "repo1", "label2", "000000")
assert(labelId == 4)
def getLabel = dummyService.getLabel("user1", "repo1", labelId)
assert(getLabel == Some(Label("user1", "repo1", labelId, "label2", "000000")))
}}
}
describe("updateLabel") {
it("should change target label") { withTestDB { implicit session =>
generateNewUserWithDBRepository("user1", "repo1")
generateNewUserWithDBRepository("user1", "repo2")
generateNewUserWithDBRepository("user2", "repo1")
val labelId = dummyService.createLabel("user1", "repo1", "label1", "000000")
dummyService.createLabel("user1", "repo2", "label1", "000000")
dummyService.createLabel("user2", "repo1", "label1", "000000")
dummyService.updateLabel("user1", "repo1", labelId, "updated-label", "ffffff")
def getLabel = dummyService.getLabel("user1", "repo1", labelId)
assert(getLabel == Some(Label("user1", "repo1", labelId, "updated-label", "ffffff")))
}}
}
describe("deleteLabel") {
it("should remove target label") { withTestDB { implicit session =>
generateNewUserWithDBRepository("user1", "repo1")
generateNewUserWithDBRepository("user1", "repo2")
generateNewUserWithDBRepository("user2", "repo1")
val labelId = dummyService.createLabel("user1", "repo1", "label1", "000000")
dummyService.createLabel("user1", "repo2", "label1", "000000")
dummyService.createLabel("user2", "repo1", "label1", "000000")
dummyService.deleteLabel("user1", "repo1", labelId)
assert(dummyService.getLabel("user1", "repo1", labelId) == None)
}}
}
}

View File

@@ -1,26 +1,17 @@
package gitbucket.core.service
import gitbucket.core.model._
import gitbucket.core.util.JGitUtil
import gitbucket.core.util.Directory._
import gitbucket.core.util.Implicits._
import gitbucket.core.util.ControlUtil._
import gitbucket.core.util.GitSpecUtil._
import org.apache.commons.io.FileUtils
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.dircache.DirCache
import org.eclipse.jgit.lib._
import org.eclipse.jgit.revwalk._
import org.eclipse.jgit.treewalk._
import org.specs2.mutable.Specification
import org.scalatest.FunSpec
import java.io.File
import java.nio.file._
import java.util.Date
class MergeServiceSpec extends Specification {
sequential
class MergeServiceSpec extends FunSpec {
val service = new MergeService{}
val branch = "master"
val issueId = 10
@@ -36,95 +27,95 @@ class MergeServiceSpec extends Specification {
createFile(git, s"refs/heads/${branch}", "test.txt", "hoge2" )
createFile(git, s"refs/pull/${issueId}/head", "test.txt", "hoge4" )
}
"checkConflict, checkConflictCache" should {
"checkConflict false if not conflicted, and create cache" in {
describe("checkConflict, checkConflictCache") {
it("checkConflict false if not conflicted, and create cache") {
val repo1Dir = initRepository("user1","repo1")
service.checkConflictCache("user1", "repo1", branch, issueId) mustEqual None
assert(service.checkConflictCache("user1", "repo1", branch, issueId) == None)
val conflicted = service.checkConflict("user1", "repo1", branch, issueId)
service.checkConflictCache("user1", "repo1", branch, issueId) mustEqual Some(false)
conflicted mustEqual false
assert(service.checkConflictCache("user1", "repo1", branch, issueId) == Some(false))
assert(conflicted == false)
}
"checkConflict true if not conflicted, and create cache" in {
val repo1Dir = initRepository("user1","repo1")
using(Git.open(repo1Dir)){ git =>
it("checkConflict true if not conflicted, and create cache") {
val repo2Dir = initRepository("user1","repo2")
using(Git.open(repo2Dir)){ git =>
createConfrict(git)
}
service.checkConflictCache("user1", "repo1", branch, issueId) mustEqual None
val conflicted = service.checkConflict("user1", "repo1", branch, issueId)
conflicted mustEqual true
service.checkConflictCache("user1", "repo1", branch, issueId) mustEqual Some(true)
assert(service.checkConflictCache("user1", "repo2", branch, issueId) == None)
val conflicted = service.checkConflict("user1", "repo2", branch, issueId)
assert(conflicted == true)
assert(service.checkConflictCache("user1", "repo2", branch, issueId) == Some(true))
}
}
"checkConflictCache" should {
"merged cache invalid if origin branch moved" in {
val repo1Dir = initRepository("user1","repo1")
service.checkConflict("user1", "repo1", branch, issueId) mustEqual false
service.checkConflictCache("user1", "repo1", branch, issueId) mustEqual Some(false)
using(Git.open(repo1Dir)){ git =>
describe("checkConflictCache") {
it("merged cache invalid if origin branch moved") {
val repo3Dir = initRepository("user1","repo3")
assert(service.checkConflict("user1", "repo3", branch, issueId) == false)
assert(service.checkConflictCache("user1", "repo3", branch, issueId) == Some(false))
using(Git.open(repo3Dir)){ git =>
createFile(git, s"refs/heads/${branch}", "test.txt", "hoge2" )
}
service.checkConflictCache("user1", "repo1", branch, issueId) mustEqual None
assert(service.checkConflictCache("user1", "repo3", branch, issueId) == None)
}
"merged cache invalid if request branch moved" in {
val repo1Dir = initRepository("user1","repo1")
service.checkConflict("user1", "repo1", branch, issueId) mustEqual false
service.checkConflictCache("user1", "repo1", branch, issueId) mustEqual Some(false)
using(Git.open(repo1Dir)){ git =>
it("merged cache invalid if request branch moved") {
val repo4Dir = initRepository("user1","repo4")
assert(service.checkConflict("user1", "repo4", branch, issueId) == false)
assert(service.checkConflictCache("user1", "repo4", branch, issueId) == Some(false))
using(Git.open(repo4Dir)){ git =>
createFile(git, s"refs/pull/${issueId}/head", "test.txt", "hoge4" )
}
service.checkConflictCache("user1", "repo1", branch, issueId) mustEqual None
assert(service.checkConflictCache("user1", "repo4", branch, issueId) == None)
}
"merged cache invalid if origin branch moved" in {
val repo1Dir = initRepository("user1","repo1")
service.checkConflict("user1", "repo1", branch, issueId) mustEqual false
service.checkConflictCache("user1", "repo1", branch, issueId) mustEqual Some(false)
using(Git.open(repo1Dir)){ git =>
it("should merged cache invalid if origin branch moved") {
val repo5Dir = initRepository("user1","repo5")
assert(service.checkConflict("user1", "repo5", branch, issueId) == false)
assert(service.checkConflictCache("user1", "repo5", branch, issueId) == Some(false))
using(Git.open(repo5Dir)){ git =>
createFile(git, s"refs/heads/${branch}", "test.txt", "hoge2" )
}
service.checkConflictCache("user1", "repo1", branch, issueId) mustEqual None
assert(service.checkConflictCache("user1", "repo5", branch, issueId) == None)
}
"conflicted cache invalid if request branch moved" in {
val repo1Dir = initRepository("user1","repo1")
using(Git.open(repo1Dir)){ git =>
it("conflicted cache invalid if request branch moved") {
val repo6Dir = initRepository("user1","repo6")
using(Git.open(repo6Dir)){ git =>
createConfrict(git)
}
service.checkConflict("user1", "repo1", branch, issueId) mustEqual true
service.checkConflictCache("user1", "repo1", branch, issueId) mustEqual Some(true)
using(Git.open(repo1Dir)){ git =>
assert(service.checkConflict("user1", "repo6", branch, issueId) == true)
assert(service.checkConflictCache("user1", "repo6", branch, issueId) == Some(true))
using(Git.open(repo6Dir)){ git =>
createFile(git, s"refs/pull/${issueId}/head", "test.txt", "hoge4" )
}
service.checkConflictCache("user1", "repo1", branch, issueId) mustEqual None
assert(service.checkConflictCache("user1", "repo6", branch, issueId) == None)
}
"conflicted cache invalid if origin branch moved" in {
val repo1Dir = initRepository("user1","repo1")
using(Git.open(repo1Dir)){ git =>
it("conflicted cache invalid if origin branch moved") {
val repo7Dir = initRepository("user1","repo7")
using(Git.open(repo7Dir)){ git =>
createConfrict(git)
}
service.checkConflict("user1", "repo1", branch, issueId) mustEqual true
service.checkConflictCache("user1", "repo1", branch, issueId) mustEqual Some(true)
using(Git.open(repo1Dir)){ git =>
assert(service.checkConflict("user1", "repo7", branch, issueId) == true)
assert(service.checkConflictCache("user1", "repo7", branch, issueId) == Some(true))
using(Git.open(repo7Dir)){ git =>
createFile(git, s"refs/heads/${branch}", "test.txt", "hoge4" )
}
service.checkConflictCache("user1", "repo1", branch, issueId) mustEqual None
assert(service.checkConflictCache("user1", "repo7", branch, issueId) == None)
}
}
"mergePullRequest" should {
"can merge" in {
val repo1Dir = initRepository("user1","repo1")
using(Git.open(repo1Dir)){ git =>
describe("mergePullRequest") {
it("can merge") {
val repo8Dir = initRepository("user1","repo8")
using(Git.open(repo8Dir)){ git =>
createFile(git, s"refs/pull/${issueId}/head", "test.txt", "hoge2" )
val committer = new PersonIdent("dummy2", "dummy2@example.com")
getFile(git, branch, "test.txt").content.get mustEqual "hoge"
assert(getFile(git, branch, "test.txt").content.get == "hoge")
val requestBranchId = git.getRepository.resolve(s"refs/pull/${issueId}/head")
val masterId = git.getRepository.resolve(branch)
service.mergePullRequest(git, branch, issueId, "merged", committer)
val lastCommitId = git.getRepository.resolve(branch);
val lastCommitId = git.getRepository.resolve(branch)
val commit = using(new RevWalk(git.getRepository))(_.parseCommit(lastCommitId))
commit.getCommitterIdent() mustEqual committer
commit.getAuthorIdent() mustEqual committer
commit.getFullMessage() mustEqual "merged"
commit.getParents.toSet mustEqual Set( requestBranchId, masterId )
getFile(git, branch, "test.txt").content.get mustEqual "hoge2"
assert(commit.getCommitterIdent() == committer)
assert(commit.getAuthorIdent() == committer)
assert(commit.getFullMessage() == "merged")
assert(commit.getParents.toSet == Set( requestBranchId, masterId ))
assert(getFile(git, branch, "test.txt").content.get == "hoge2")
}
}
}

View File

@@ -0,0 +1,189 @@
package gitbucket.core.service
import gitbucket.core.util.GitSpecUtil._
import org.eclipse.jgit.transport.{ReceivePack, ReceiveCommand}
import org.eclipse.jgit.lib.ObjectId
import gitbucket.core.model.CommitState
import gitbucket.core.service.ProtectedBranchService.{ProtectedBranchReceiveHook, ProtectedBranchInfo}
import org.scalatest.FunSpec
class ProtectedBranchServiceSpec extends FunSpec with ServiceSpecBase with ProtectedBranchService with CommitStatusService {
val receiveHook = new ProtectedBranchReceiveHook()
val now = new java.util.Date()
val sha = "0c77148632618b59b6f70004e3084002be2b8804"
val sha2 = "0c77148632618b59b6f70004e3084002be2b8805"
describe("getProtectedBranchInfo") {
it("should empty is disabled") {
withTestDB { implicit session =>
assert(getProtectedBranchInfo("user1", "repo1", "branch") == ProtectedBranchInfo.disabled("user1", "repo1"))
}
}
it("should enable and update and disable") {
withTestDB { implicit session =>
generateNewUserWithDBRepository("user1", "repo1")
enableBranchProtection("user1", "repo1", "branch", false, Nil)
assert(getProtectedBranchInfo("user1", "repo1", "branch") == ProtectedBranchInfo("user1", "repo1", true, Nil, false))
enableBranchProtection("user1", "repo1", "branch", true, Seq("hoge","huge"))
assert(getProtectedBranchInfo("user1", "repo1", "branch") == ProtectedBranchInfo("user1", "repo1", true, Seq("hoge","huge"), true))
disableBranchProtection("user1", "repo1", "branch")
assert(getProtectedBranchInfo("user1", "repo1", "branch") == ProtectedBranchInfo.disabled("user1", "repo1"))
}
}
it("should empty contexts is no-include-administrators") {
withTestDB { implicit session =>
generateNewUserWithDBRepository("user1", "repo1")
enableBranchProtection("user1", "repo1", "branch", false, Nil)
assert(getProtectedBranchInfo("user1", "repo1", "branch").includeAdministrators == false)
enableBranchProtection("user1", "repo1", "branch", true, Nil)
assert(getProtectedBranchInfo("user1", "repo1", "branch").includeAdministrators == false)
}
}
it("getProtectedBranchList") {
withTestDB { implicit session =>
generateNewUserWithDBRepository("user1", "repo1")
enableBranchProtection("user1", "repo1", "branch", false, Nil)
enableBranchProtection("user1", "repo1", "branch2", false, Seq("fuga"))
enableBranchProtection("user1", "repo1", "branch3", true, Seq("hoge"))
assert(getProtectedBranchList("user1", "repo1").toSet == Set("branch", "branch2", "branch3"))
}
}
it("getBranchProtectedReason on force push from admin") {
withTestDB { implicit session =>
withTestRepository { git =>
val rp = new ReceivePack(git.getRepository)
rp.setAllowNonFastForwards(true)
val rc = new ReceiveCommand(ObjectId.fromString(sha), ObjectId.fromString(sha2), "refs/heads/branch", ReceiveCommand.Type.UPDATE_NONFASTFORWARD)
generateNewUserWithDBRepository("user1", "repo1")
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user1") == None)
enableBranchProtection("user1", "repo1", "branch", false, Nil)
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user1") == Some("Cannot force-push to a protected branch"))
}
}
}
it("getBranchProtectedReason on force push from other") {
withTestDB { implicit session =>
withTestRepository { git =>
val rp = new ReceivePack(git.getRepository)
rp.setAllowNonFastForwards(true)
val rc = new ReceiveCommand(ObjectId.fromString(sha), ObjectId.fromString(sha2), "refs/heads/branch", ReceiveCommand.Type.UPDATE_NONFASTFORWARD)
generateNewUserWithDBRepository("user1", "repo1")
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user2") == None)
enableBranchProtection("user1", "repo1", "branch", false, Nil)
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user2") == Some("Cannot force-push to a protected branch"))
}
}
}
it("getBranchProtectedReason check status on push from other") {
withTestDB { implicit session =>
withTestRepository { git =>
val rp = new ReceivePack(git.getRepository)
rp.setAllowNonFastForwards(false)
val rc = new ReceiveCommand(ObjectId.fromString(sha), ObjectId.fromString(sha2), "refs/heads/branch", ReceiveCommand.Type.UPDATE)
val user1 = generateNewUserWithDBRepository("user1", "repo1")
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user2") == None)
enableBranchProtection("user1", "repo1", "branch", false, Seq("must"))
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user2") == Some("Required status check \"must\" is expected"))
enableBranchProtection("user1", "repo1", "branch", false, Seq("must", "must2"))
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user2") == Some("2 of 2 required status checks are expected"))
createCommitStatus("user1", "repo1", sha2, "context", CommitState.SUCCESS, None, None, now, user1)
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user2") == Some("2 of 2 required status checks are expected"))
createCommitStatus("user1", "repo1", sha2, "must", CommitState.SUCCESS, None, None, now, user1)
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user2") == Some("Required status check \"must2\" is expected"))
createCommitStatus("user1", "repo1", sha2, "must2", CommitState.SUCCESS, None, None, now, user1)
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user2") == None)
}
}
}
it("getBranchProtectedReason check status on push from admin") {
withTestDB { implicit session =>
withTestRepository { git =>
val rp = new ReceivePack(git.getRepository)
rp.setAllowNonFastForwards(false)
val rc = new ReceiveCommand(ObjectId.fromString(sha), ObjectId.fromString(sha2), "refs/heads/branch", ReceiveCommand.Type.UPDATE)
val user1 = generateNewUserWithDBRepository("user1", "repo1")
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user1") == None)
enableBranchProtection("user1", "repo1", "branch", false, Seq("must"))
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user1") == None)
enableBranchProtection("user1", "repo1", "branch", true, Seq("must"))
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user1") == Some("Required status check \"must\" is expected"))
enableBranchProtection("user1", "repo1", "branch", false, Seq("must", "must2"))
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user1") == None)
enableBranchProtection("user1", "repo1", "branch", true, Seq("must", "must2"))
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user1") == Some("2 of 2 required status checks are expected"))
createCommitStatus("user1", "repo1", sha2, "context", CommitState.SUCCESS, None, None, now, user1)
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user1") == Some("2 of 2 required status checks are expected"))
createCommitStatus("user1", "repo1", sha2, "must", CommitState.SUCCESS, None, None, now, user1)
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user1") == Some("Required status check \"must2\" is expected"))
createCommitStatus("user1", "repo1", sha2, "must2", CommitState.SUCCESS, None, None, now, user1)
assert(receiveHook.preReceive("user1", "repo1", rp, rc, "user1") == None)
}
}
}
}
describe("ProtectedBranchInfo") {
it("administrator is owner") {
withTestDB { implicit session =>
generateNewUserWithDBRepository("user1", "repo1")
val x = ProtectedBranchInfo("user1", "repo1", true, Nil, false)
assert(x.isAdministrator("user1") == true)
assert(x.isAdministrator("user2") == false)
}
}
it("administrator is manager") {
withTestDB { implicit session =>
val x = ProtectedBranchInfo("grp1", "repo1", true, Nil, false)
x.createGroup("grp1", None, None)
generateNewAccount("user1")
generateNewAccount("user2")
generateNewAccount("user3")
x.updateGroupMembers("grp1", List("user1"->true, "user2"->false))
assert(x.isAdministrator("user1") == true)
assert(x.isAdministrator("user2") == false)
assert(x.isAdministrator("user3") == false)
}
}
it("unSuccessedContexts") {
withTestDB { implicit session =>
val user1 = generateNewUserWithDBRepository("user1", "repo1")
val x = ProtectedBranchInfo("user1", "repo1", true, List("must"), false)
assert(x.unSuccessedContexts(sha) == Set("must"))
createCommitStatus("user1", "repo1", sha, "context", CommitState.SUCCESS, None, None, now, user1)
assert(x.unSuccessedContexts(sha) == Set("must"))
createCommitStatus("user1", "repo1", sha, "must", CommitState.ERROR, None, None, now, user1)
assert(x.unSuccessedContexts(sha) == Set("must"))
createCommitStatus("user1", "repo1", sha, "must", CommitState.PENDING, None, None, now, user1)
assert(x.unSuccessedContexts(sha) == Set("must"))
createCommitStatus("user1", "repo1", sha, "must", CommitState.FAILURE, None, None, now, user1)
assert(x.unSuccessedContexts(sha) == Set("must"))
createCommitStatus("user1", "repo1", sha, "must", CommitState.SUCCESS, None, None, now, user1)
assert(x.unSuccessedContexts(sha) == Set())
}
}
it("unSuccessedContexts when empty") {
withTestDB { implicit session =>
val user1 = generateNewUserWithDBRepository("user1", "repo1")
val x = ProtectedBranchInfo("user1", "repo1", true, Nil, false)
val sha = "0c77148632618b59b6f70004e3084002be2b8804"
assert(x.unSuccessedContexts(sha) == Set())
createCommitStatus("user1", "repo1", sha, "context", CommitState.SUCCESS, None, None, now, user1)
assert(x.unSuccessedContexts(sha) == Set())
}
}
it("if disabled, needStatusCheck is false") {
withTestDB { implicit session =>
assert(ProtectedBranchInfo("user1", "repo1", false, Seq("must"), true).needStatusCheck("user1") == false)
}
}
it("needStatusCheck includeAdministrators") {
withTestDB { implicit session =>
assert(ProtectedBranchInfo("user1", "repo1", true, Seq("must"), false).needStatusCheck("user2") == true)
assert(ProtectedBranchInfo("user1", "repo1", true, Seq("must"), false).needStatusCheck("user1") == false)
assert(ProtectedBranchInfo("user1", "repo1", true, Seq("must"), true ).needStatusCheck("user2") == true)
assert(ProtectedBranchInfo("user1", "repo1", true, Seq("must"), true ).needStatusCheck("user1") == true)
}
}
}
}

View File

@@ -1,17 +1,18 @@
package gitbucket.core.service
import gitbucket.core.model._
import gitbucket.core.model.Profile._
import org.scalatest.FunSpec
import org.specs2.mutable.Specification
class PullRequestServiceSpec extends FunSpec with ServiceSpecBase
with PullRequestService with IssuesService with AccountService with RepositoryService with CommitsService {
class PullRequestServiceSpec extends Specification with ServiceSpecBase with PullRequestService with IssuesService {
def swap(r: (Issue, PullRequest)) = (r._2 -> r._1)
"PullRequestService.getPullRequestFromBranch" should {
"""
describe("PullRequestService.getPullRequestFromBranch") {
it("""should
|return pull request if exists pull request from `branch` to `defaultBranch` and not closed.
|return pull request if exists pull request from `branch` to othre branch and not closed.
|return None if all pull request is closed""".stripMargin.trim in { withTestDB { implicit se =>
|return None if all pull request is closed""".stripMargin.trim) { withTestDB { implicit se =>
generateNewUserWithDBRepository("user1", "repo1")
generateNewUserWithDBRepository("user1", "repo2")
generateNewUserWithDBRepository("user2", "repo1")
@@ -22,12 +23,12 @@ class PullRequestServiceSpec extends Specification with ServiceSpecBase with Pul
val r1 = swap(generateNewPullRequest("user1/repo1/master2", "user1/repo1/head1"))
val r2 = swap(generateNewPullRequest("user1/repo1/master", "user1/repo1/head1"))
val r3 = swap(generateNewPullRequest("user1/repo1/master4", "user1/repo1/head1"))
getPullRequestFromBranch("user1", "repo1", "head1", "master") must_== Some(r2)
assert(getPullRequestFromBranch("user1", "repo1", "head1", "master") == Some(r2))
updateClosed("user1", "repo1", r2._1.issueId, true)
getPullRequestFromBranch("user1", "repo1", "head1", "master").get must beOneOf(r1, r2)
assert(Seq(r1, r2).contains(getPullRequestFromBranch("user1", "repo1", "head1", "master").get))
updateClosed("user1", "repo1", r1._1.issueId, true)
updateClosed("user1", "repo1", r3._1.issueId, true)
getPullRequestFromBranch("user1", "repo1", "head1", "master") must beNone
assert(getPullRequestFromBranch("user1", "repo1", "head1", "master") == None)
} }
}
}

View File

@@ -1,35 +1,33 @@
package gitbucket.core.service
import gitbucket.core.model._
import gitbucket.core.model.Profile._
import org.scalatest.FunSuite
import org.specs2.mutable.Specification
class RepositoryServiceSpec extends FunSuite with ServiceSpecBase with RepositoryService with AccountService{
test("renameRepository can rename CommitState, ProtectedBranches") { withTestDB { implicit session =>
val tester = generateNewAccount("tester")
insertRepository("repo", "root", None, false)
val service = new CommitStatusService with ProtectedBranchService {}
val id = service.createCommitStatus(
userName = "root",
repositoryName = "repo",
sha = "0e97b8f59f7cdd709418bb59de53f741fd1c1bd7",
context = "jenkins/test",
state = CommitState.PENDING,
targetUrl = Some("http://example.com/target"),
description = Some("description"),
creator = tester,
now = new java.util.Date)
service.enableBranchProtection("root", "repo", "branch", true, Seq("must1", "must2"))
class RepositoryServiceSpec extends Specification with ServiceSpecBase with RepositoryService with AccountService{
"RepositoryService" should {
"renameRepository can rename CommitState" in { withTestDB { implicit session =>
val tester = generateNewAccount("tester")
createRepository("repo","root",None,false)
val commitStatusService = new CommitStatusService{}
val id = commitStatusService.createCommitStatus(
userName = "root",
repositoryName = "repo",
sha = "0e97b8f59f7cdd709418bb59de53f741fd1c1bd7",
context = "jenkins/test",
state = CommitState.PENDING,
targetUrl = Some("http://example.com/target"),
description = Some("description"),
creator = tester,
now = new java.util.Date)
val org = commitStatusService.getCommitStatus("root","repo", id).get
renameRepository("root","repo","tester","repo2")
val neo = commitStatusService.getCommitStatus("tester","repo2", org.commitId, org.context).get
neo must_==
org.copy(
commitStatusId=neo.commitStatusId,
repositoryName="repo2",
userName="tester")
}}
}
val orgPbi = service.getProtectedBranchInfo("root", "repo", "branch")
val org = service.getCommitStatus("root","repo", id).get
renameRepository("root","repo","tester","repo2")
val neo = service.getCommitStatus("tester","repo2", org.commitId, org.context).get
assert(neo == org.copy(commitStatusId = neo.commitStatusId, repositoryName = "repo2", userName = "tester"))
assert(service.getProtectedBranchInfo("tester", "repo2", "branch") == orgPbi.copy(owner = "tester", repository = "repo2"))
}}
}

View File

@@ -1,10 +1,13 @@
package gitbucket.core.service
import gitbucket.core.servlet.AutoUpdate
import gitbucket.core.util.{ControlUtil, DatabaseConfig, FileUtil}
import gitbucket.core.GitBucketCoreModule
import gitbucket.core.util.{DatabaseConfig, FileUtil}
import gitbucket.core.util.ControlUtil._
import gitbucket.core.model._
import gitbucket.core.model.Profile._
import io.github.gitbucket.solidbase.Solidbase
import liquibase.database.core.H2Database
import liquibase.database.jvm.JdbcConnection
import profile.simple._
import org.apache.commons.io.FileUtils
@@ -22,7 +25,10 @@ trait ServiceSpecBase {
val (url, user, pass) = (DatabaseConfig.url(Some(dir.toString)), DatabaseConfig.user, DatabaseConfig.password)
org.h2.Driver.load()
using(DriverManager.getConnection(url, user, pass)){ conn =>
AutoUpdate.versions.reverse.foreach(_.update(conn, Thread.currentThread.getContextClassLoader))
val solidbase = new Solidbase()
val db = new H2Database()
db.setConnection(new JdbcConnection(conn)) // TODO Remove setConnection in the future
solidbase.migrate(conn, Thread.currentThread.getContextClassLoader, db, GitBucketCoreModule)
}
Database.forURL(url, user, pass).withSession { session =>
action(session)
@@ -38,16 +44,16 @@ trait ServiceSpecBase {
def user(name:String)(implicit s:Session):Account = AccountService.getAccountByUserName(name).get
lazy val dummyService = new RepositoryService with AccountService with IssuesService with PullRequestService
with CommitStatusService (){}
with CommitsService with CommitStatusService with LabelsService (){}
def generateNewUserWithDBRepository(userName:String, repositoryName:String)(implicit s:Session):Account = {
val ac = AccountService.getAccountByUserName(userName).getOrElse(generateNewAccount(userName))
dummyService.createRepository(repositoryName, userName, None, false)
dummyService.insertRepository(repositoryName, userName, None, false)
ac
}
def generateNewIssue(userName:String, repositoryName:String, loginUser:String="root")(implicit s:Session): Int = {
dummyService.createIssue(
dummyService.insertIssue(
owner = userName,
repository = repositoryName,
loginUser = loginUser,

View File

@@ -1,44 +1,79 @@
package gitbucket.core.service
import org.specs2.mutable.Specification
import gitbucket.core.model.WebHook
import org.scalatest.FunSuite
import gitbucket.core.model.WebHookContentType
class WebHookServiceSpec extends Specification with ServiceSpecBase {
lazy val service = new WebHookPullRequestService with AccountService with RepositoryService with PullRequestService with IssuesService
class WebHookServiceSpec extends FunSuite with ServiceSpecBase {
lazy val service = new WebHookPullRequestService with AccountService with RepositoryService with PullRequestService with IssuesService with CommitsService
"WebHookPullRequestService.getPullRequestsByRequestForWebhook" should {
"find from request branch" in { withTestDB { implicit session =>
val user1 = generateNewUserWithDBRepository("user1","repo1")
val user2 = generateNewUserWithDBRepository("user2","repo2")
val user3 = generateNewUserWithDBRepository("user3","repo3")
val issueUser = user("root")
val (issue1, pullreq1) = generateNewPullRequest("user1/repo1/master1", "user2/repo2/master2", loginUser="root")
val (issue3, pullreq3) = generateNewPullRequest("user3/repo3/master3", "user2/repo2/master2", loginUser="root")
val (issue32, pullreq32) = generateNewPullRequest("user3/repo3/master32", "user2/repo2/master2", loginUser="root")
generateNewPullRequest("user2/repo2/master2", "user1/repo1/master2")
service.addWebHookURL("user1", "repo1", "webhook1-1")
service.addWebHookURL("user1", "repo1", "webhook1-2")
service.addWebHookURL("user2", "repo2", "webhook2-1")
service.addWebHookURL("user2", "repo2", "webhook2-2")
service.addWebHookURL("user3", "repo3", "webhook3-1")
service.addWebHookURL("user3", "repo3", "webhook3-2")
test("WebHookPullRequestService.getPullRequestsByRequestForWebhook") { withTestDB { implicit session =>
val user1 = generateNewUserWithDBRepository("user1","repo1")
val user2 = generateNewUserWithDBRepository("user2","repo2")
val user3 = generateNewUserWithDBRepository("user3","repo3")
val issueUser = user("root")
val (issue1, pullreq1) = generateNewPullRequest("user1/repo1/master1", "user2/repo2/master2", loginUser="root")
val (issue3, pullreq3) = generateNewPullRequest("user3/repo3/master3", "user2/repo2/master2", loginUser="root")
val (issue32, pullreq32) = generateNewPullRequest("user3/repo3/master32", "user2/repo2/master2", loginUser="root")
generateNewPullRequest("user2/repo2/master2", "user1/repo1/master2")
service.addWebHook("user1", "repo1", "webhook1-1", Set(WebHook.PullRequest), WebHookContentType.FORM, Some("key"))
service.addWebHook("user1", "repo1", "webhook1-2", Set(WebHook.PullRequest), WebHookContentType.FORM, Some("key"))
service.addWebHook("user2", "repo2", "webhook2-1", Set(WebHook.PullRequest), WebHookContentType.FORM, Some("key"))
service.addWebHook("user2", "repo2", "webhook2-2", Set(WebHook.PullRequest), WebHookContentType.FORM, Some("key"))
service.addWebHook("user3", "repo3", "webhook3-1", Set(WebHook.PullRequest), WebHookContentType.FORM, Some("key"))
service.addWebHook("user3", "repo3", "webhook3-2", Set(WebHook.PullRequest), WebHookContentType.FORM, Some("key"))
service.getPullRequestsByRequestForWebhook("user1","repo1","master1") must_== Map.empty
assert(service.getPullRequestsByRequestForWebhook("user1","repo1","master1") == Map.empty)
var r = service.getPullRequestsByRequestForWebhook("user2","repo2","master2").mapValues(_.map(_.url).toSet)
val r = service.getPullRequestsByRequestForWebhook("user2","repo2","master2").mapValues(_.map(_.url).toSet)
r.size must_== 3
r((issue1, issueUser, pullreq1, user1, user2)) must_== Set("webhook1-1","webhook1-2")
r((issue3, issueUser, pullreq3, user3, user2)) must_== Set("webhook3-1","webhook3-2")
r((issue32, issueUser, pullreq32, user3, user2)) must_== Set("webhook3-1","webhook3-2")
assert(r.size == 3)
assert(r((issue1, issueUser, pullreq1, user1, user2)) == Set("webhook1-1","webhook1-2"))
assert(r((issue3, issueUser, pullreq3, user3, user2)) == Set("webhook3-1","webhook3-2"))
assert(r((issue32, issueUser, pullreq32, user3, user2)) == Set("webhook3-1","webhook3-2"))
// when closed, it not founds.
service.updateClosed("user1","repo1",issue1.issueId, true)
// when closed, it not founds.
service.updateClosed("user1","repo1",issue1.issueId, true)
var r2 = service.getPullRequestsByRequestForWebhook("user2","repo2","master2").mapValues(_.map(_.url).toSet)
r2.size must_== 2
r2((issue3, issueUser, pullreq3, user3, user2)) must_== Set("webhook3-1","webhook3-2")
r2((issue32, issueUser, pullreq32, user3, user2)) must_== Set("webhook3-1","webhook3-2")
} }
}
val r2 = service.getPullRequestsByRequestForWebhook("user2","repo2","master2").mapValues(_.map(_.url).toSet)
assert(r2.size == 2)
assert(r2((issue3, issueUser, pullreq3, user3, user2)) == Set("webhook3-1","webhook3-2"))
assert(r2((issue32, issueUser, pullreq32, user3, user2)) == Set("webhook3-1","webhook3-2"))
} }
test("add and get and update and delete") { withTestDB { implicit session =>
val user1 = generateNewUserWithDBRepository("user1","repo1")
val formType = WebHookContentType.FORM
val jsonType = WebHookContentType.JSON
service.addWebHook("user1", "repo1", "http://example.com", Set(WebHook.PullRequest), formType, Some("key"))
assert(service.getWebHooks("user1", "repo1") == List((WebHook("user1","repo1","http://example.com", formType, Some("key")),Set(WebHook.PullRequest))))
assert(service.getWebHook("user1", "repo1", "http://example.com") == Some((WebHook("user1","repo1","http://example.com", formType, Some("key")),Set(WebHook.PullRequest))))
assert(service.getWebHooksByEvent("user1", "repo1", WebHook.PullRequest) == List((WebHook("user1","repo1","http://example.com", formType, Some("key")))))
assert(service.getWebHooksByEvent("user1", "repo1", WebHook.Push) == Nil)
assert(service.getWebHook("user1", "repo1", "http://example.com2") == None)
assert(service.getWebHook("user2", "repo1", "http://example.com") == None)
assert(service.getWebHook("user1", "repo2", "http://example.com") == None)
service.updateWebHook("user1", "repo1", "http://example.com", Set(WebHook.Push, WebHook.Issues), jsonType, Some("key"))
assert(service.getWebHook("user1", "repo1", "http://example.com") == Some((WebHook("user1","repo1","http://example.com", jsonType, Some("key")),Set(WebHook.Push, WebHook.Issues))))
assert(service.getWebHooksByEvent("user1", "repo1", WebHook.PullRequest) == Nil)
assert(service.getWebHooksByEvent("user1", "repo1", WebHook.Push) == List((WebHook("user1","repo1","http://example.com", jsonType, Some("key")))))
service.deleteWebHook("user1", "repo1", "http://example.com")
assert(service.getWebHook("user1", "repo1", "http://example.com") == None)
} }
test("getWebHooks, getWebHooksByEvent") { withTestDB { implicit session =>
val user1 = generateNewUserWithDBRepository("user1","repo1")
val ctype = WebHookContentType.FORM
service.addWebHook("user1", "repo1", "http://example.com/1", Set(WebHook.PullRequest), ctype, Some("key"))
service.addWebHook("user1", "repo1", "http://example.com/2", Set(WebHook.Push), ctype, Some("key"))
service.addWebHook("user1", "repo1", "http://example.com/3", Set(WebHook.PullRequest,WebHook.Push), ctype, Some("key"))
assert(service.getWebHooks("user1", "repo1") == List(
WebHook("user1","repo1","http://example.com/1", ctype, Some("key"))->Set(WebHook.PullRequest),
WebHook("user1","repo1","http://example.com/2", ctype, Some("key"))->Set(WebHook.Push),
WebHook("user1","repo1","http://example.com/3", ctype, Some("key"))->Set(WebHook.PullRequest,WebHook.Push)))
assert(service.getWebHooksByEvent("user1", "repo1", WebHook.PullRequest) == List(
WebHook("user1","repo1","http://example.com/1", ctype, Some("key")),
WebHook("user1","repo1","http://example.com/3", ctype, Some("key"))))
} }
}

View File

@@ -1,39 +1,35 @@
package gitbucket.core.ssh
import org.specs2.mutable._
import org.specs2.mock.Mockito
import org.apache.sshd.server.command.UnknownCommand
import javax.servlet.ServletContext
import org.apache.sshd.server.scp.UnknownCommand
import org.scalatest.FunSpec
class GitCommandFactorySpec extends Specification with Mockito {
class GitCommandFactorySpec extends FunSpec {
val factory = new GitCommandFactory("http://localhost:8080")
"createCommand" should {
"returns GitReceivePack when command is git-receive-pack" in {
factory.createCommand("git-receive-pack '/owner/repo.git'").isInstanceOf[GitReceivePack] must beTrue
factory.createCommand("git-receive-pack '/owner/repo.wiki.git'").isInstanceOf[GitReceivePack] must beTrue
describe("createCommand") {
it("should return GitReceivePack when command is git-receive-pack"){
assert(factory.createCommand("git-receive-pack '/owner/repo.git'").isInstanceOf[DefaultGitReceivePack] == true)
assert(factory.createCommand("git-receive-pack '/owner/repo.wiki.git'").isInstanceOf[DefaultGitReceivePack] == true)
}
"returns GitUploadPack when command is git-upload-pack" in {
factory.createCommand("git-upload-pack '/owner/repo.git'").isInstanceOf[GitUploadPack] must beTrue
factory.createCommand("git-upload-pack '/owner/repo.wiki.git'").isInstanceOf[GitUploadPack] must beTrue
it("should return GitUploadPack when command is git-upload-pack"){
assert(factory.createCommand("git-upload-pack '/owner/repo.git'").isInstanceOf[DefaultGitUploadPack] == true)
assert(factory.createCommand("git-upload-pack '/owner/repo.wiki.git'").isInstanceOf[DefaultGitUploadPack] == true)
}
"returns UnknownCommand when command is not git-(upload|receive)-pack" in {
factory.createCommand("git- '/owner/repo.git'").isInstanceOf[UnknownCommand] must beTrue
factory.createCommand("git-pack '/owner/repo.git'").isInstanceOf[UnknownCommand] must beTrue
factory.createCommand("git-a-pack '/owner/repo.git'").isInstanceOf[UnknownCommand] must beTrue
factory.createCommand("git-up-pack '/owner/repo.git'").isInstanceOf[UnknownCommand] must beTrue
factory.createCommand("\ngit-upload-pack '/owner/repo.git'").isInstanceOf[UnknownCommand] must beTrue
it("should return UnknownCommand when command is not git-(upload|receive)-pack"){
assert(factory.createCommand("git- '/owner/repo.git'").isInstanceOf[UnknownCommand] == true)
assert(factory.createCommand("git-pack '/owner/repo.git'").isInstanceOf[UnknownCommand] == true)
assert(factory.createCommand("git-a-pack '/owner/repo.git'").isInstanceOf[UnknownCommand] == true)
assert(factory.createCommand("git-up-pack '/owner/repo.git'").isInstanceOf[UnknownCommand] == true)
assert(factory.createCommand("\ngit-upload-pack '/owner/repo.git'").isInstanceOf[UnknownCommand] == true)
}
"returns UnknownCommand when git command has no valid arguments" in {
it("should return UnknownCommand when git command has no valid arguments"){
// must be: git-upload-pack '/owner/repository_name.git'
factory.createCommand("git-upload-pack").isInstanceOf[UnknownCommand] must beTrue
factory.createCommand("git-upload-pack /owner/repo.git").isInstanceOf[UnknownCommand] must beTrue
factory.createCommand("git-upload-pack 'owner/repo.git'").isInstanceOf[UnknownCommand] must beTrue
factory.createCommand("git-upload-pack '/ownerrepo.git'").isInstanceOf[UnknownCommand] must beTrue
factory.createCommand("git-upload-pack '/owner/repo.wiki'").isInstanceOf[UnknownCommand] must beTrue
assert(factory.createCommand("git-upload-pack").isInstanceOf[UnknownCommand] == true)
assert(factory.createCommand("git-upload-pack /owner/repo.git").isInstanceOf[UnknownCommand] == true)
assert(factory.createCommand("git-upload-pack 'owner/repo.git'").isInstanceOf[UnknownCommand] == true)
assert(factory.createCommand("git-upload-pack '/ownerrepo.git'").isInstanceOf[UnknownCommand] == true)
assert(factory.createCommand("git-upload-pack '/owner/repo.wiki'").isInstanceOf[UnknownCommand] == true)
}
}

View File

@@ -1,15 +1,16 @@
package gitbucket.core.util
import org.specs2.mutable._
import org.scalatest.FunSpec
class DirectorySpec extends FunSpec {
class DirectorySpec extends Specification {
"GitBucketHome" should {
"set under target in test scope" in {
Directory.GitBucketHome mustEqual new java.io.File("target/gitbucket_home_for_test").getAbsolutePath
}
"exists" in {
new java.io.File(Directory.GitBucketHome).exists
describe("GitBucketHome"){
it("should set under target in test scope"){
assert(Directory.GitBucketHome == new java.io.File("target/gitbucket_home_for_test").getAbsolutePath)
}
}
// test("GitBucketHome should exists"){
// new java.io.File(Directory.GitBucketHome).exists
// }
}

View File

@@ -1,7 +1,5 @@
package gitbucket.core.util
import gitbucket.core.model._
import gitbucket.core.util.Directory._
import gitbucket.core.util.ControlUtil._
import org.apache.commons.io.FileUtils
@@ -14,14 +12,13 @@ import org.eclipse.jgit.merge._
import org.eclipse.jgit.errors._
import java.nio.file._
import java.util.Date
import java.io.File
object GitSpecUtil {
def withTestFolder[U](f: File => U) {
def withTestFolder[U](f: File => U): U = {
val folder = new File(System.getProperty("java.io.tmpdir"), "test-" + System.nanoTime)
if(!folder.mkdirs()){
throw new java.io.IOException("can't create folder "+folder.getAbsolutePath)
throw new java.io.IOException("can't create folder " + folder.getAbsolutePath)
}
try {
f(folder)
@@ -29,7 +26,7 @@ object GitSpecUtil {
FileUtils.deleteQuietly(folder)
}
}
def withTestRepository[U](f: Git => U) = withTestFolder(folder => using(Git.open(createTestRepository(folder)))(f))
def withTestRepository[U](f: Git => U): U = withTestFolder(folder => using(Git.open(createTestRepository(folder)))(f))
def createTestRepository(dir: File): File = {
RepositoryCache.clear()
FileUtils.deleteQuietly(dir)
@@ -56,7 +53,7 @@ object GitSpecUtil {
JGitUtil.createNewCommit(git, inserter, headId, builder.getDirCache.writeTree(inserter),
branch, autorName, autorEmail, message)
inserter.flush()
inserter.release()
inserter.close()
}
def getFile(git: Git, branch: String, path: String) = {
val revCommit = JGitUtil.getRevCommitFromId(git, git.getRepository.resolve(branch))
@@ -99,7 +96,7 @@ object GitSpecUtil {
val inserter = repository.newObjectInserter
val mergeCommitId = inserter.insert(mergeCommit)
inserter.flush()
inserter.release()
inserter.close()
// update refs
val refUpdate = repository.updateRef(into)
refUpdate.setNewObjectId(mergeCommitId)

View File

@@ -1,103 +1,104 @@
package gitbucket.core.util
import org.specs2.mutable._
import GitSpecUtil._
import org.scalatest.FunSuite
class JGitUtilSpec extends Specification {
class JGitUtilSpec extends FunSuite {
"getFileList(git: Git, revision: String, path)" should {
test("getFileList(git: Git, revision: String, path)"){
withTestRepository { git =>
def list(branch: String, path: String) =
JGitUtil.getFileList(git, branch, path).map(finfo => (finfo.name, finfo.message, finfo.isDirectory))
list("master", ".") mustEqual Nil
list("master", "dir/subdir") mustEqual Nil
list("branch", ".") mustEqual Nil
list("branch", "dir/subdir") mustEqual Nil
assert(list("master", ".") == Nil)
assert(list("master", "dir/subdir") == Nil)
assert(list("branch", ".") == Nil)
assert(list("branch", "dir/subdir") == Nil)
createFile(git, "master", "README.md", "body1", message = "commit1")
list("master", ".") mustEqual List(("README.md", "commit1", false))
list("master", "dir/subdir") mustEqual Nil
list("branch", ".") mustEqual Nil
list("branch", "dir/subdir") mustEqual Nil
assert(list("master", ".") == List(("README.md", "commit1", false)))
assert(list("master", "dir/subdir") == Nil)
assert(list("branch", ".") == Nil)
assert(list("branch", "dir/subdir") == Nil)
createFile(git, "master", "README.md", "body2", message = "commit2")
list("master", ".") mustEqual List(("README.md", "commit2", false))
list("master", "dir/subdir") mustEqual Nil
list("branch", ".") mustEqual Nil
list("branch", "dir/subdir") mustEqual Nil
assert(list("master", ".") == List(("README.md", "commit2", false)))
assert(list("master", "dir/subdir") == Nil)
assert(list("branch", ".") == Nil)
assert(list("branch", "dir/subdir") == Nil)
createFile(git, "master", "dir/subdir/File3.md", "body3", message = "commit3")
list("master", ".") mustEqual List(("dir/subdir", "commit3", true), ("README.md", "commit2", false))
list("master", "dir/subdir") mustEqual List(("File3.md", "commit3", false))
list("branch", ".") mustEqual Nil
list("branch", "dir/subdir") mustEqual Nil
assert(list("master", ".") == List(("dir/subdir", "commit3", true), ("README.md", "commit2", false)))
assert(list("master", "dir/subdir") == List(("File3.md", "commit3", false)))
assert(list("branch", ".") == Nil)
assert(list("branch", "dir/subdir") == Nil)
createFile(git, "master", "dir/subdir/File4.md", "body4", message = "commit4")
list("master", ".") mustEqual List(("dir/subdir", "commit4", true), ("README.md", "commit2", false))
list("master", "dir/subdir") mustEqual List(("File3.md", "commit3", false), ("File4.md", "commit4", false))
list("branch", ".") mustEqual Nil
list("branch", "dir/subdir") mustEqual Nil
assert(list("master", ".") == List(("dir/subdir", "commit4", true), ("README.md", "commit2", false)))
assert(list("master", "dir/subdir") == List(("File3.md", "commit3", false), ("File4.md", "commit4", false)))
assert(list("branch", ".") == Nil)
assert(list("branch", "dir/subdir") == Nil)
createFile(git, "master", "README5.md", "body5", message = "commit5")
list("master", ".") mustEqual List(("dir/subdir", "commit4", true), ("README.md", "commit2", false), ("README5.md", "commit5", false))
list("master", "dir/subdir") mustEqual List(("File3.md", "commit3", false), ("File4.md", "commit4", false))
list("branch", ".") mustEqual Nil
list("branch", "dir/subdir") mustEqual Nil
assert(list("master", ".") == List(("dir/subdir", "commit4", true), ("README.md", "commit2", false), ("README5.md", "commit5", false)))
assert(list("master", "dir/subdir") == List(("File3.md", "commit3", false), ("File4.md", "commit4", false)))
assert(list("branch", ".") == Nil)
assert(list("branch", "dir/subdir") == Nil)
createFile(git, "master", "README.md", "body6", message = "commit6")
list("master", ".") mustEqual List(("dir/subdir", "commit4", true), ("README.md", "commit6", false), ("README5.md", "commit5", false))
list("master", "dir/subdir") mustEqual List(("File3.md", "commit3", false), ("File4.md", "commit4", false))
list("branch", ".") mustEqual Nil
list("branch", "dir/subdir") mustEqual Nil
assert(list("master", ".") == List(("dir/subdir", "commit4", true), ("README.md", "commit6", false), ("README5.md", "commit5", false)))
assert(list("master", "dir/subdir") == List(("File3.md", "commit3", false), ("File4.md", "commit4", false)))
assert(list("branch", ".") == Nil)
assert(list("branch", "dir/subdir") == Nil)
git.branchCreate().setName("branch").setStartPoint("master").call()
list("master", ".") mustEqual List(("dir/subdir", "commit4", true), ("README.md", "commit6", false), ("README5.md", "commit5", false))
list("master", "dir/subdir") mustEqual List(("File3.md", "commit3", false), ("File4.md", "commit4", false))
list("branch", ".") mustEqual List(("dir/subdir", "commit4", true), ("README.md", "commit6", false), ("README5.md", "commit5", false))
list("branch", "dir/subdir") mustEqual List(("File3.md", "commit3", false), ("File4.md", "commit4", false))
assert(list("master", ".") == List(("dir/subdir", "commit4", true), ("README.md", "commit6", false), ("README5.md", "commit5", false)))
assert(list("master", "dir/subdir") == List(("File3.md", "commit3", false), ("File4.md", "commit4", false)))
assert(list("branch", ".") == List(("dir/subdir", "commit4", true), ("README.md", "commit6", false), ("README5.md", "commit5", false)))
assert(list("branch", "dir/subdir") == List(("File3.md", "commit3", false), ("File4.md", "commit4", false)))
createFile(git, "branch", "dir/subdir/File3.md", "body7", message = "commit7")
list("master", ".") mustEqual List(("dir/subdir", "commit4", true), ("README.md", "commit6", false), ("README5.md", "commit5", false))
list("master", "dir/subdir") mustEqual List(("File3.md", "commit3", false), ("File4.md", "commit4", false))
list("branch", ".") mustEqual List(("dir/subdir", "commit7", true), ("README.md", "commit6", false), ("README5.md", "commit5", false))
list("branch", "dir/subdir") mustEqual List(("File3.md", "commit7", false), ("File4.md", "commit4", false))
assert(list("master", ".") == List(("dir/subdir", "commit4", true), ("README.md", "commit6", false), ("README5.md", "commit5", false)))
assert(list("master", "dir/subdir") == List(("File3.md", "commit3", false), ("File4.md", "commit4", false)))
assert(list("branch", ".") == List(("dir/subdir", "commit7", true), ("README.md", "commit6", false), ("README5.md", "commit5", false)))
assert(list("branch", "dir/subdir") == List(("File3.md", "commit7", false), ("File4.md", "commit4", false)))
createFile(git, "master", "dir8/File8.md", "body8", message = "commit8")
list("master", ".") mustEqual List(("dir/subdir", "commit4", true), ("dir8", "commit8", true), ("README.md", "commit6", false), ("README5.md", "commit5", false))
list("master", "dir/subdir") mustEqual List(("File3.md", "commit3", false), ("File4.md", "commit4", false))
list("branch", ".") mustEqual List(("dir/subdir", "commit7", true), ("README.md", "commit6", false), ("README5.md", "commit5", false))
list("branch", "dir/subdir") mustEqual List(("File3.md", "commit7", false), ("File4.md", "commit4", false))
assert(list("master", ".") == List(("dir/subdir", "commit4", true), ("dir8", "commit8", true), ("README.md", "commit6", false), ("README5.md", "commit5", false)))
assert(list("master", "dir/subdir") == List(("File3.md", "commit3", false), ("File4.md", "commit4", false)))
assert(list("branch", ".") == List(("dir/subdir", "commit7", true), ("README.md", "commit6", false), ("README5.md", "commit5", false)))
assert(list("branch", "dir/subdir") == List(("File3.md", "commit7", false), ("File4.md", "commit4", false)))
createFile(git, "branch", "dir/subdir9/File9.md", "body9", message = "commit9")
list("master", ".") mustEqual List(("dir/subdir", "commit4", true), ("dir8", "commit8", true), ("README.md", "commit6", false), ("README5.md", "commit5", false))
list("master", "dir/subdir") mustEqual List(("File3.md", "commit3", false), ("File4.md", "commit4", false))
list("branch", ".") mustEqual List(("dir", "commit9", true), ("README.md", "commit6", false), ("README5.md", "commit5", false))
list("branch", "dir/subdir") mustEqual List(("File3.md", "commit7", false), ("File4.md", "commit4", false))
assert(list("master", ".") == List(("dir/subdir", "commit4", true), ("dir8", "commit8", true), ("README.md", "commit6", false), ("README5.md", "commit5", false)))
assert(list("master", "dir/subdir") == List(("File3.md", "commit3", false), ("File4.md", "commit4", false)))
assert(list("branch", ".") == List(("dir", "commit9", true), ("README.md", "commit6", false), ("README5.md", "commit5", false)))
assert(list("branch", "dir/subdir") == List(("File3.md", "commit7", false), ("File4.md", "commit4", false)))
mergeAndCommit(git, "master", "branch", message = "merge10")
list("master", ".") mustEqual List(("dir", "commit9", true), ("dir8", "commit8", true), ("README.md", "commit6", false), ("README5.md", "commit5", false))
list("master", "dir/subdir") mustEqual List(("File3.md", "commit7", false), ("File4.md", "commit4", false))
assert(list("master", ".") == List(("dir", "commit9", true), ("dir8", "commit8", true), ("README.md", "commit6", false), ("README5.md", "commit5", false)))
assert(list("master", "dir/subdir") == List(("File3.md", "commit7", false), ("File4.md", "commit4", false)))
}
}
"getFileList subfolder multi-origin (issue #721)" should {
test("getFileList subfolder multi-origin (issue #721)") {
withTestRepository { git =>
def list(branch: String, path: String) =
JGitUtil.getFileList(git, branch, path).map(finfo => (finfo.name, finfo.message, finfo.isDirectory))
createFile(git, "master", "README.md", "body1", message = "commit1")
createFile(git, "branch", "test/text2.txt", "body2", message = "commit2")
mergeAndCommit(git, "master", "branch", message = "merge3")
list("master", "test") mustEqual List(("text2.txt", "commit2", false))
assert(list("master", "test") == List(("text2.txt", "commit2", false)))
}
}
}

View File

@@ -1,56 +1,66 @@
package gitbucket.core.util
import org.specs2.mutable._
import org.scalatest.FunSpec
class StringUtilSpec extends Specification {
class StringUtilSpec extends FunSpec {
"urlDecode" should {
"decode encoded string to original string" in {
describe("urlEncode") {
it("should encode whitespace to %20") {
val encoded = StringUtil.urlEncode("aa bb")
assert(encoded == "aa%20bb")
}
}
describe("urlDecode") {
it("should decode encoded string to original string") {
val encoded = StringUtil.urlEncode("あいうえお")
StringUtil.urlDecode(encoded) mustEqual "あいうえお"
assert(StringUtil.urlDecode(encoded) == "あいうえお")
}
it("should decode en%20 to whitespace") {
assert(StringUtil.urlDecode("aa%20bb") == "aa bb")
}
}
"splitWords" should {
"split string by whitespaces" in {
describe("splitWords") {
it("should split string by whitespaces") {
val split = StringUtil.splitWords("aa bb\tcc dd \t ee")
split mustEqual Array("aa", "bb", "cc", "dd", "ee")
assert(split === Array("aa", "bb", "cc", "dd", "ee"))
}
}
"escapeHtml" should {
"escape &, <, > and \"" in {
StringUtil.escapeHtml("<a href=\"/test\">a & b</a>") mustEqual "&lt;a href=&quot;/test&quot;&gt;a &amp; b&lt;/a&gt;"
describe("escapeHtml") {
it("should escape &, <, > and \"") {
assert(StringUtil.escapeHtml("<a href=\"/test\">a & b</a>") == "&lt;a href=&quot;/test&quot;&gt;a &amp; b&lt;/a&gt;")
}
}
"md5" should {
"generate MD5 hash" in {
StringUtil.md5("abc") mustEqual "900150983cd24fb0d6963f7d28e17f72"
describe("md5") {
it("should generate MD5 hash") {
assert(StringUtil.md5("abc") == "900150983cd24fb0d6963f7d28e17f72")
}
}
"sha1" should {
"generate SHA1 hash" in {
StringUtil.sha1("abc") mustEqual "a9993e364706816aba3e25717850c26c9cd0d89d"
describe("sha1") {
it("should generate SHA1 hash") {
assert(StringUtil.sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d")
}
}
"extractIssueId" should {
"extract '#xxx' and return extracted id" in {
StringUtil.extractIssueId("(refs #123)").toSeq mustEqual Seq("123")
describe("extractIssueId") {
it("should extract '#xxx' and return extracted id") {
assert(StringUtil.extractIssueId("(refs #123)").toSeq == Seq("123"))
}
"returns Nil from message which does not contain #xxx" in {
StringUtil.extractIssueId("this is test!").toSeq mustEqual Nil
it("should return Nil from message which does not contain #xxx") {
assert(StringUtil.extractIssueId("this is test!").toSeq == Nil)
}
}
"extractCloseId" should {
"extract 'close #xxx' and return extracted id" in {
StringUtil.extractCloseId("(close #123)").toSeq mustEqual Seq("123")
describe("extractCloseId") {
it("should extract 'close #xxx' and return extracted id") {
assert(StringUtil.extractCloseId("(close #123)").toSeq == Seq("123"))
}
"returns Nil from message which does not contain close command" in {
StringUtil.extractCloseId("(refs #123)").toSeq mustEqual Nil
it("should returns Nil from message which does not contain close command") {
assert(StringUtil.extractCloseId("(refs #123)").toSeq == Nil)
}
}
}

View File

@@ -1,35 +1,35 @@
package gitbucket.core.util
import org.specs2.mutable._
import org.scalatra.i18n.Messages
import org.scalatest.FunSpec
class ValidationsSpec extends Specification with Validations {
class ValidationsSpec extends FunSpec with Validations {
"identifier" should {
"validate id string " in {
identifier.validate("id", "aa_ZZ-00.01", null) mustEqual None
identifier.validate("id", "_aaaa", null) mustEqual Some("id starts with invalid character.")
identifier.validate("id", "-aaaa", null) mustEqual Some("id starts with invalid character.")
identifier.validate("id", "aa_ZZ#01", null) mustEqual Some("id contains invalid character.")
describe("identifier") {
it("should validate id string ") {
assert(identifier.validate("id", "aa_ZZ-00.01", null) == None)
assert(identifier.validate("id", "_aaaa", null) == Some("id starts with invalid character."))
assert(identifier.validate("id", "-aaaa", null) == Some("id starts with invalid character."))
assert(identifier.validate("id", "aa_ZZ#01", null) == Some("id contains invalid character."))
}
}
"color" should {
"validate color string " in {
describe("color") {
it("should validate color string ") {
val messages = Messages()
color.validate("color", "#88aaff", messages) mustEqual None
color.validate("color", "#gghhii", messages) mustEqual Some("color must be '#[0-9a-fA-F]{6}'.")
assert(color.validate("color", "#88aaff", messages) == None)
assert(color.validate("color", "#gghhii", messages) == Some("color must be '#[0-9a-fA-F]{6}'."))
}
}
"date" should {
describe("date") {
// "validate date string " in {
// date().validate("date", "2013-10-05", Map[String, String]()) mustEqual Nil
// date().validate("date", "2013-10-5" , Map[String, String]()) mustEqual List(("date", "date must be '\\d{4}-\\d{2}-\\d{2}'."))
// }
"convert date string " in {
it("should convert date string ") {
val result = date().convert("2013-10-05", null)
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(result) mustEqual "2013-10-05 00:00:00"
assert(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(result) == "2013-10-05 00:00:00")
}
}

View File

@@ -3,76 +3,81 @@ package gitbucket.core.view
import java.util.Date
import gitbucket.core.model.Account
import gitbucket.core.service.{SystemSettingsService, RequestCache}
import gitbucket.core.service.{RequestCache, SystemSettingsService}
import gitbucket.core.controller.Context
import org.specs2.mutable._
import org.specs2.mock.Mockito
import SystemSettingsService.SystemSettings
import javax.servlet.http.HttpServletRequest
import play.twirl.api.Html
import javax.servlet.http.{HttpServletRequest, HttpSession}
class AvatarImageProviderSpec extends Specification with Mockito {
import play.twirl.api.Html
import org.scalatest.FunSpec
import org.scalatest.mock.MockitoSugar
import org.mockito.Mockito._
class AvatarImageProviderSpec extends FunSpec with MockitoSugar {
val request = mock[HttpServletRequest]
request.getRequestURL returns new StringBuffer("http://localhost:8080/path.html")
request.getRequestURI returns "/path.html"
request.getContextPath returns ""
val session = mock[HttpSession]
when(request.getRequestURL).thenReturn(new StringBuffer("http://localhost:8080/path.html"))
when(request.getRequestURI).thenReturn("/path.html")
when(request.getContextPath).thenReturn("")
when(request.getSession).thenReturn(session)
"getAvatarImageHtml" should {
"show Gravatar image for no image account if gravatar integration is enabled" in {
describe("getAvatarImageHtml") {
it("should show Gravatar image for no image account if gravatar integration is enabled") {
implicit val context = Context(createSystemSettings(true), None, request)
val provider = new AvatarImageProviderImpl(Some(createAccount(None)))
provider.toHtml("user", 32).toString mustEqual
"<img src=\"https://www.gravatar.com/avatar/d41d8cd98f00b204e9800998ecf8427e?s=32&d=retro&r=g\" class=\"avatar\" style=\"width: 32px; height: 32px;\" />"
assert(provider.toHtml("user", 32).toString ==
"<img src=\"https://www.gravatar.com/avatar/d41d8cd98f00b204e9800998ecf8427e?s=32&d=retro&r=g\" class=\"avatar\" style=\"width: 32px; height: 32px;\" />")
}
"show uploaded image even if gravatar integration is enabled" in {
it("should show uploaded image even if gravatar integration is enabled") {
implicit val context = Context(createSystemSettings(true), None, request)
val provider = new AvatarImageProviderImpl(Some(createAccount(Some("icon.png"))))
provider.toHtml("user", 32).toString mustEqual
"<img src=\"/user/_avatar\" class=\"avatar\" style=\"width: 32px; height: 32px;\" />"
assert(provider.toHtml("user", 32).toString ==
"<img src=\"/user/_avatar\" class=\"avatar\" style=\"width: 32px; height: 32px;\" />")
}
"show local image for no image account if gravatar integration is disabled" in {
it("should show local image for no image account if gravatar integration is disabled") {
implicit val context = Context(createSystemSettings(false), None, request)
val provider = new AvatarImageProviderImpl(Some(createAccount(None)))
provider.toHtml("user", 32).toString mustEqual
"<img src=\"/user/_avatar\" class=\"avatar\" style=\"width: 32px; height: 32px;\" />"
assert(provider.toHtml("user", 32).toString ==
"<img src=\"/user/_avatar\" class=\"avatar\" style=\"width: 32px; height: 32px;\" />")
}
"show Gravatar image for specified mail address if gravatar integration is enabled" in {
it("should show Gravatar image for specified mail address if gravatar integration is enabled") {
implicit val context = Context(createSystemSettings(true), None, request)
val provider = new AvatarImageProviderImpl(None)
provider.toHtml("user", 20, "hoge@hoge.com").toString mustEqual
"<img src=\"https://www.gravatar.com/avatar/4712f9b0e63f56ad952ad387eaa23b9c?s=20&d=retro&r=g\" class=\"avatar-mini\" style=\"width: 20px; height: 20px;\" />"
assert(provider.toHtml("user", 20, "hoge@hoge.com").toString ==
"<img src=\"https://www.gravatar.com/avatar/4712f9b0e63f56ad952ad387eaa23b9c?s=20&d=retro&r=g\" class=\"avatar-mini\" style=\"width: 20px; height: 20px;\" />")
}
"show unknown image for unknown user if gravatar integration is enabled" in {
it("should show unknown image for unknown user if gravatar integration is enabled") {
implicit val context = Context(createSystemSettings(true), None, request)
val provider = new AvatarImageProviderImpl(None)
provider.toHtml("user", 20).toString mustEqual
"<img src=\"/_unknown/_avatar\" class=\"avatar-mini\" style=\"width: 20px; height: 20px;\" />"
assert(provider.toHtml("user", 20).toString ==
"<img src=\"/_unknown/_avatar\" class=\"avatar-mini\" style=\"width: 20px; height: 20px;\" />")
}
"show unknown image for specified mail address if gravatar integration is disabled" in {
it("should show unknown image for specified mail address if gravatar integration is disabled") {
implicit val context = Context(createSystemSettings(false), None, request)
val provider = new AvatarImageProviderImpl(None)
provider.toHtml("user", 20, "hoge@hoge.com").toString mustEqual
"<img src=\"/_unknown/_avatar\" class=\"avatar-mini\" style=\"width: 20px; height: 20px;\" />"
assert(provider.toHtml("user", 20, "hoge@hoge.com").toString ==
"<img src=\"/_unknown/_avatar\" class=\"avatar-mini\" style=\"width: 20px; height: 20px;\" />")
}
"add tooltip if it's enabled" in {
it("should add tooltip if it's enabled") {
implicit val context = Context(createSystemSettings(false), None, request)
val provider = new AvatarImageProviderImpl(None)
provider.toHtml("user", 20, "hoge@hoge.com", true).toString mustEqual
"<img src=\"/_unknown/_avatar\" class=\"avatar-mini\" style=\"width: 20px; height: 20px;\" data-toggle=\"tooltip\" title=\"user\"/>"
assert(provider.toHtml("user", 20, "hoge@hoge.com", true).toString ==
"<img src=\"/_unknown/_avatar\" class=\"avatar-mini\" style=\"width: 20px; height: 20px;\" data-toggle=\"tooltip\" title=\"user\"/>")
}
}
@@ -103,7 +108,9 @@ class AvatarImageProviderSpec extends Specification with Mockito {
notification = false,
activityLogLimit = None,
ssh = false,
sshHost = None,
sshPort = None,
useSMTP = false,
smtp = None,
ldapAuthentication = false,
ldap = None)

View File

@@ -1,93 +0,0 @@
package gitbucket.core.view
import org.specs2.mutable._
class GitBucketHtmlSerializerSpec extends Specification {
import GitBucketHtmlSerializer._
"generateAnchorName" should {
"convert whitespace characters to hyphens" in {
val before = "foo bar baz"
val after = generateAnchorName(before)
after mustEqual "foo-bar-baz"
}
"normalize characters with diacritics" in {
val before = "Dónde estará mi vida"
val after = generateAnchorName(before)
after mustEqual "do%cc%81nde-estara%cc%81-mi-vida"
}
"omit special characters" in {
val before = "foo!bar@baz>9000"
val after = generateAnchorName(before)
after mustEqual "foo%21bar%40baz%3e9000"
}
}
"escapeTaskList" should {
"convert '- [ ] ' to '* task: :'" in {
val before = "- [ ] aaaa"
val after = escapeTaskList(before)
after mustEqual "* task: : aaaa"
}
"convert ' - [ ] ' to ' * task: :'" in {
val before = " - [ ] aaaa"
val after = escapeTaskList(before)
after mustEqual " * task: : aaaa"
}
"convert only first '- [ ] '" in {
val before = " - [ ] aaaa - [ ] bbb"
val after = escapeTaskList(before)
after mustEqual " * task: : aaaa - [ ] bbb"
}
"convert '- [x] ' to '* task:x:'" in {
val before = " - [x] aaaa"
val after = escapeTaskList(before)
after mustEqual " * task:x: aaaa"
}
"convert multi lines" in {
val before = """
tasks
- [x] aaaa
- [ ] bbb
"""
val after = escapeTaskList(before)
after mustEqual """
tasks
* task:x: aaaa
* task: : bbb
"""
}
"no convert if inserted before '- [ ] '" in {
val before = " a - [ ] aaaa"
val after = escapeTaskList(before)
after mustEqual " a - [ ] aaaa"
}
"no convert '- [] '" in {
val before = " - [] aaaa"
val after = escapeTaskList(before)
after mustEqual " - [] aaaa"
}
"no convert '- [ ]a'" in {
val before = " - [ ]a aaaa"
val after = escapeTaskList(before)
after mustEqual " - [ ]a aaaa"
}
"no convert '-[ ] '" in {
val before = " -[ ] aaaa"
val after = escapeTaskList(before)
after mustEqual " -[ ] aaaa"
}
}
}

View File

@@ -0,0 +1,65 @@
package gitbucket.core.view
import gitbucket.core.controller.Context
import gitbucket.core.service.RepositoryService.RepositoryInfo
import org.scalatest.FunSpec
import org.scalatest.mock.MockitoSugar
class HelpersSpec extends FunSpec with MockitoSugar {
private implicit val context = mock[Context]
private val repository = mock[RepositoryInfo]
import helpers._
describe("detect and render links") {
it("should pass identical string when no link is present") {
val before = "Description"
val after = detectAndRenderLinks(before, repository)
assert(after == before)
}
it("should convert a single link") {
val before = "http://example.com"
val after = detectAndRenderLinks(before, repository)
assert(after == """<a href="http://example.com">http://example.com</a>""")
}
it("should convert a single link within trailing text") {
val before = "Example Project. http://example.com"
val after = detectAndRenderLinks(before, repository)
assert(after == """Example Project. <a href="http://example.com">http://example.com</a>""")
}
it("should convert a mulitple links within text") {
val before = "Example Project. http://example.com. (See also https://github.com/)"
val after = detectAndRenderLinks(before, repository)
assert(after == """Example Project. <a href="http://example.com">http://example.com</a>. (See also <a href="https://github.com/">https://github.com/</a>)""")
}
it("should properly escape html metacharacters") {
val before = "<>&"
val after = detectAndRenderLinks(before, repository)
assert(after == """&lt;&gt;&amp;""")
}
it("should escape html metacharacters adjacent to a link") {
val before = "<http://example.com>"
val after = detectAndRenderLinks(before, repository)
assert(after == """&lt;<a href="http://example.com">http://example.com</a>&gt;""")
}
it("should stop link recognition at a metacharacter") {
val before = "http://exa<mple.com"
val after = detectAndRenderLinks(before, repository)
assert(after == """<a href="http://exa">http://exa</a>&lt;mple.com""")
}
it("should make sure there are no double quotes in the href attribute") {
val before = "http://exa\"mple.com"
val after = detectAndRenderLinks(before, repository)
assert(after == """<a href="http://exa&quot;mple.com">http://exa"mple.com</a>""")
}
}
}

View File

@@ -0,0 +1,93 @@
package gitbucket.core.view
import org.scalatest.FunSpec
class MarkdownSpec extends FunSpec {
import Markdown._
describe("generateAnchorName") {
it("should convert whitespace characters to hyphens") {
val before = "foo bar baz"
val after = generateAnchorName(before)
assert(after == "foo-bar-baz")
}
it("should normalize characters with diacritics") {
val before = "Dónde estará mi vida"
val after = generateAnchorName(before)
assert(after == "do%cc%81nde-estara%cc%81-mi-vida")
}
it("should omit special characters") {
val before = "foo!bar@baz>9000"
val after = generateAnchorName(before)
assert(after == "foo%21bar%40baz%3e9000")
}
}
describe("escapeTaskList") {
it("should convert '- [ ] ' to '* task: :'") {
val before = "- [ ] aaaa"
val after = escapeTaskList(before)
assert(after == "* task: : aaaa")
}
it("should convert ' - [ ] ' to ' * task: :'") {
val before = " - [ ] aaaa"
val after = escapeTaskList(before)
assert(after == " * task: : aaaa")
}
it("should convert only first '- [ ] '") {
val before = " - [ ] aaaa - [ ] bbb"
val after = escapeTaskList(before)
assert(after == " * task: : aaaa - [ ] bbb")
}
it("should convert '- [x] ' to '* task:x:'") {
val before = " - [x] aaaa"
val after = escapeTaskList(before)
assert(after == " * task:x: aaaa")
}
it("should convert multi lines") {
val before = """
tasks
- [x] aaaa
- [ ] bbb
"""
val after = escapeTaskList(before)
assert(after == """
tasks
* task:x: aaaa
* task: : bbb
""")
}
it("should not convert if inserted before '- [ ] '") {
val before = " a - [ ] aaaa"
val after = escapeTaskList(before)
assert(after == " a - [ ] aaaa")
}
it("should not convert '- [] '") {
val before = " - [] aaaa"
val after = escapeTaskList(before)
assert(after == " - [] aaaa")
}
it("should not convert '- [ ]a'") {
val before = " - [ ]a aaaa"
val after = escapeTaskList(before)
assert(after == " - [ ]a aaaa")
}
it("should not convert '-[ ] '") {
val before = " -[ ] aaaa"
val after = escapeTaskList(before)
assert(after == " -[ ] aaaa")
}
}
}

View File

@@ -1,68 +1,68 @@
package gitbucket.core.view
import gitbucket.core.util.ControlUtil
import org.specs2.mutable._
import ControlUtil._
import org.scalatest.FunSpec
class PaginationSpec extends Specification {
class PaginationSpec extends FunSpec {
"max" should {
"return max page number" in {
describe("max") {
it("should return max page number") {
val pagination = Pagination(1, 100, 10, 6)
pagination.max mustEqual 10
assert(pagination.max == 10)
}
}
"omitLeft and omitRight" should {
"return true if pagination links at their side will be omitted" in {
describe("omitLeft and omitRight") {
it("should return true if pagination links at their side will be omitted") {
defining(Pagination(1, 100, 10, 6)){ pagination =>
pagination.omitLeft mustEqual false
pagination.omitRight mustEqual true
assert(pagination.omitLeft == false)
assert(pagination.omitRight == true)
}
defining(Pagination(9, 100, 10, 6)){ pagination =>
pagination.omitLeft mustEqual true
pagination.omitRight mustEqual false
assert(pagination.omitLeft == true)
assert(pagination.omitRight == false)
}
}
}
"visibleFor" should {
"return true for visible pagination links" in {
describe("visibleFor") {
it("should return true for visible pagination links") {
defining(Pagination(1, 100, 10, 6)){ pagination =>
pagination.visibleFor(1) mustEqual true
pagination.visibleFor(2) mustEqual true
pagination.visibleFor(3) mustEqual true
pagination.visibleFor(4) mustEqual true
pagination.visibleFor(5) mustEqual true
pagination.visibleFor(6) mustEqual false
pagination.visibleFor(7) mustEqual false
pagination.visibleFor(8) mustEqual false
pagination.visibleFor(9) mustEqual false
pagination.visibleFor(10) mustEqual true
assert(pagination.visibleFor(1) == true)
assert(pagination.visibleFor(2) == true)
assert(pagination.visibleFor(3) == true)
assert(pagination.visibleFor(4) == true)
assert(pagination.visibleFor(5) == true)
assert(pagination.visibleFor(6) == false)
assert(pagination.visibleFor(7) == false)
assert(pagination.visibleFor(8) == false)
assert(pagination.visibleFor(9) == false)
assert(pagination.visibleFor(10) == true)
}
defining(Pagination(5, 100, 10, 6)){ pagination =>
pagination.visibleFor(1) mustEqual true
pagination.visibleFor(2) mustEqual false
pagination.visibleFor(3) mustEqual false
pagination.visibleFor(4) mustEqual true
pagination.visibleFor(5) mustEqual true
pagination.visibleFor(6) mustEqual true
pagination.visibleFor(7) mustEqual false
pagination.visibleFor(8) mustEqual false
pagination.visibleFor(9) mustEqual false
pagination.visibleFor(10) mustEqual true
assert(pagination.visibleFor(1) == true)
assert(pagination.visibleFor(2) == false)
assert(pagination.visibleFor(3) == false)
assert(pagination.visibleFor(4) == true)
assert(pagination.visibleFor(5) == true)
assert(pagination.visibleFor(6) == true)
assert(pagination.visibleFor(7) == false)
assert(pagination.visibleFor(8) == false)
assert(pagination.visibleFor(9) == false)
assert(pagination.visibleFor(10) == true)
}
defining(Pagination(8, 100, 10, 6)){ pagination =>
pagination.visibleFor(1) mustEqual true
pagination.visibleFor(2) mustEqual false
pagination.visibleFor(3) mustEqual false
pagination.visibleFor(4) mustEqual false
pagination.visibleFor(5) mustEqual false
pagination.visibleFor(6) mustEqual true
pagination.visibleFor(7) mustEqual true
pagination.visibleFor(8) mustEqual true
pagination.visibleFor(9) mustEqual true
pagination.visibleFor(10) mustEqual true
assert(pagination.visibleFor(1) == true)
assert(pagination.visibleFor(2) == false)
assert(pagination.visibleFor(3) == false)
assert(pagination.visibleFor(4) == false)
assert(pagination.visibleFor(5) == false)
assert(pagination.visibleFor(6) == true)
assert(pagination.visibleFor(7) == true)
assert(pagination.visibleFor(8) == true)
assert(pagination.visibleFor(9) == true)
assert(pagination.visibleFor(10) == true)
}
}
}