* prerequisites

* storetest package
Этот коммит содержится в:
Chris
2017-10-06 11:08:59 -07:00
коммит произвёл GitHub
родитель d1958bdc49
Коммит 70e5f00241
46 изменённых файлов: 11093 добавлений и 11069 удалений

Просмотреть файл

@@ -12,4 +12,6 @@ const (
USER_SEARCH_OPTION_NAMES_ONLY_NO_FULL_NAME = "names_only_no_full_name"
USER_SEARCH_OPTION_ALL_NO_FULL_NAME = "all_no_full_name"
USER_SEARCH_OPTION_ALLOW_INACTIVE = "allow_inactive"
FEATURE_TOGGLE_PREFIX = "feature_enabled_"
)

Просмотреть файл

@@ -5,86 +5,10 @@ package sqlstore
import (
"testing"
"time"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestSqlAuditStore(t *testing.T) {
ss := Setup()
audit := &model.Audit{UserId: model.NewId(), IpAddress: "ipaddress", Action: "Action"}
store.Must(ss.Audit().Save(audit))
time.Sleep(100 * time.Millisecond)
store.Must(ss.Audit().Save(audit))
time.Sleep(100 * time.Millisecond)
store.Must(ss.Audit().Save(audit))
time.Sleep(100 * time.Millisecond)
audit.ExtraInfo = "extra"
time.Sleep(100 * time.Millisecond)
store.Must(ss.Audit().Save(audit))
time.Sleep(100 * time.Millisecond)
c := ss.Audit().Get(audit.UserId, 0, 100)
result := <-c
audits := result.Data.(model.Audits)
if len(audits) != 4 {
t.Fatal("Failed to save and retrieve 4 audit logs")
}
if audits[0].ExtraInfo != "extra" {
t.Fatal("Failed to save property for extra info")
}
c = ss.Audit().Get("missing", 0, 100)
result = <-c
audits = result.Data.(model.Audits)
if len(audits) != 0 {
t.Fatal("Should have returned empty because user_id is missing")
}
c = ss.Audit().Get("", 0, 100)
result = <-c
audits = result.Data.(model.Audits)
if len(audits) < 4 {
t.Fatal("Failed to save and retrieve 4 audit logs")
}
if r2 := <-ss.Audit().PermanentDeleteByUser(audit.UserId); r2.Err != nil {
t.Fatal(r2.Err)
}
}
func TestAuditStorePermanentDeleteBatch(t *testing.T) {
ss := Setup()
a1 := &model.Audit{UserId: model.NewId(), IpAddress: "ipaddress", Action: "Action"}
store.Must(ss.Audit().Save(a1))
time.Sleep(10 * time.Millisecond)
a2 := &model.Audit{UserId: a1.UserId, IpAddress: "ipaddress", Action: "Action"}
store.Must(ss.Audit().Save(a2))
time.Sleep(10 * time.Millisecond)
cutoff := model.GetMillis()
time.Sleep(10 * time.Millisecond)
a3 := &model.Audit{UserId: a1.UserId, IpAddress: "ipaddress", Action: "Action"}
store.Must(ss.Audit().Save(a3))
if r := <-ss.Audit().Get(a1.UserId, 0, 100); len(r.Data.(model.Audits)) != 3 {
t.Fatal("Expected 3 audits. Got ", len(r.Data.(model.Audits)))
}
store.Must(ss.Audit().PermanentDeleteBatch(cutoff, 1000000))
if r := <-ss.Audit().Get(a1.UserId, 0, 100); len(r.Data.(model.Audits)) != 1 {
t.Fatal("Expected 1 audit. Got ", len(r.Data.(model.Audits)))
}
if r2 := <-ss.Audit().PermanentDeleteByUser(a1.UserId); r2.Err != nil {
t.Fatal(r2.Err)
}
func TestAuditStore(t *testing.T) {
StoreTest(t, storetest.TestAuditStore)
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@@ -6,197 +6,9 @@ package sqlstore
import (
"testing"
"time"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestSqlClusterDiscoveryStore(t *testing.T) {
ss := Setup()
discovery := &model.ClusterDiscovery{
ClusterName: "cluster_name",
Hostname: "hostname" + model.NewId(),
Type: "test_test",
}
if result := <-ss.ClusterDiscovery().Save(discovery); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.ClusterDiscovery().Cleanup(); result.Err != nil {
t.Fatal(result.Err)
}
}
func TestSqlClusterDiscoveryStoreDelete(t *testing.T) {
ss := Setup()
discovery := &model.ClusterDiscovery{
ClusterName: "cluster_name",
Hostname: "hostname" + model.NewId(),
Type: "test_test",
}
if result := <-ss.ClusterDiscovery().Save(discovery); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.ClusterDiscovery().Delete(discovery); result.Err != nil {
t.Fatal(result.Err)
}
}
func TestSqlClusterDiscoveryStoreLastPing(t *testing.T) {
ss := Setup()
discovery := &model.ClusterDiscovery{
ClusterName: "cluster_name_lastPing",
Hostname: "hostname" + model.NewId(),
Type: "test_test_lastPing" + model.NewId(),
}
if result := <-ss.ClusterDiscovery().Save(discovery); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.ClusterDiscovery().SetLastPingAt(discovery); result.Err != nil {
t.Fatal(result.Err)
}
ttime := model.GetMillis()
time.Sleep(1 * time.Second)
if result := <-ss.ClusterDiscovery().SetLastPingAt(discovery); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.ClusterDiscovery().GetAll(discovery.Type, "cluster_name_lastPing"); result.Err != nil {
t.Fatal(result.Err)
} else {
list := result.Data.([]*model.ClusterDiscovery)
if len(list) != 1 {
t.Fatal("should only be 1 items")
return
}
if list[0].LastPingAt-ttime < 500 {
t.Fatal("failed to set time")
}
}
discovery2 := &model.ClusterDiscovery{
ClusterName: "cluster_name_missing",
Hostname: "hostname" + model.NewId(),
Type: "test_test_missing",
}
if result := <-ss.ClusterDiscovery().SetLastPingAt(discovery2); result.Err != nil {
t.Fatal(result.Err)
}
}
func TestSqlClusterDiscoveryStoreExists(t *testing.T) {
ss := Setup()
discovery := &model.ClusterDiscovery{
ClusterName: "cluster_name_Exists",
Hostname: "hostname" + model.NewId(),
Type: "test_test_Exists" + model.NewId(),
}
if result := <-ss.ClusterDiscovery().Save(discovery); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.ClusterDiscovery().Exists(discovery); result.Err != nil {
t.Fatal(result.Err)
} else {
val := result.Data.(bool)
if !val {
t.Fatal("should be true")
}
}
discovery.ClusterName = "cluster_name_Exists2"
if result := <-ss.ClusterDiscovery().Exists(discovery); result.Err != nil {
t.Fatal(result.Err)
} else {
val := result.Data.(bool)
if val {
t.Fatal("should be true")
}
}
}
func TestSqlClusterDiscoveryGetStore(t *testing.T) {
ss := Setup()
testType1 := model.NewId()
discovery1 := &model.ClusterDiscovery{
ClusterName: "cluster_name",
Hostname: "hostname1",
Type: testType1,
}
store.Must(ss.ClusterDiscovery().Save(discovery1))
discovery2 := &model.ClusterDiscovery{
ClusterName: "cluster_name",
Hostname: "hostname2",
Type: testType1,
}
store.Must(ss.ClusterDiscovery().Save(discovery2))
discovery3 := &model.ClusterDiscovery{
ClusterName: "cluster_name",
Hostname: "hostname3",
Type: testType1,
CreateAt: 1,
LastPingAt: 1,
}
store.Must(ss.ClusterDiscovery().Save(discovery3))
testType2 := model.NewId()
discovery4 := &model.ClusterDiscovery{
ClusterName: "cluster_name",
Hostname: "hostname1",
Type: testType2,
}
store.Must(ss.ClusterDiscovery().Save(discovery4))
if result := <-ss.ClusterDiscovery().GetAll(testType1, "cluster_name"); result.Err != nil {
t.Fatal(result.Err)
} else {
list := result.Data.([]*model.ClusterDiscovery)
if len(list) != 2 {
t.Fatal("Should only have returned 2")
}
}
if result := <-ss.ClusterDiscovery().GetAll(testType2, "cluster_name"); result.Err != nil {
t.Fatal(result.Err)
} else {
list := result.Data.([]*model.ClusterDiscovery)
if len(list) != 1 {
t.Fatal("Should only have returned 1")
}
}
if result := <-ss.ClusterDiscovery().GetAll(model.NewId(), "cluster_name"); result.Err != nil {
t.Fatal(result.Err)
} else {
list := result.Data.([]*model.ClusterDiscovery)
if len(list) != 0 {
t.Fatal("shouldn't be any")
}
}
func TestClusterDiscoveryStore(t *testing.T) {
StoreTest(t, storetest.TestClusterDiscoveryStore)
}

Просмотреть файл

@@ -1,4 +1,4 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package sqlstore
@@ -6,252 +6,9 @@ package sqlstore
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestCommandStoreSave(t *testing.T) {
ss := Setup()
o1 := model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger"
if err := (<-ss.Command().Save(&o1)).Err; err != nil {
t.Fatal("couldn't save item", err)
}
if err := (<-ss.Command().Save(&o1)).Err; err == nil {
t.Fatal("shouldn't be able to update from save")
}
}
func TestCommandStoreGet(t *testing.T) {
ss := Setup()
o1 := &model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger"
o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-ss.Command().Get(o1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.Command).CreateAt != o1.CreateAt {
t.Fatal("invalid returned command")
}
}
if err := (<-ss.Command().Get("123")).Err; err == nil {
t.Fatal("Missing id should have failed")
}
}
func TestCommandStoreGetByTeam(t *testing.T) {
ss := Setup()
o1 := &model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger"
o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-ss.Command().GetByTeam(o1.TeamId); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.([]*model.Command)[0].CreateAt != o1.CreateAt {
t.Fatal("invalid returned command")
}
}
if result := <-ss.Command().GetByTeam("123"); result.Err != nil {
t.Fatal(result.Err)
} else {
if len(result.Data.([]*model.Command)) != 0 {
t.Fatal("no commands should have returned")
}
}
}
func TestCommandStoreGetByTrigger(t *testing.T) {
ss := Setup()
o1 := &model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger1"
o2 := &model.Command{}
o2.CreatorId = model.NewId()
o2.Method = model.COMMAND_METHOD_POST
o2.TeamId = model.NewId()
o2.URL = "http://nowhere.com/"
o2.Trigger = "trigger1"
o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
o2 = (<-ss.Command().Save(o2)).Data.(*model.Command)
if r1 := <-ss.Command().GetByTrigger(o1.TeamId, o1.Trigger); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.Command).Id != o1.Id {
t.Fatal("invalid returned command")
}
}
store.Must(ss.Command().Delete(o1.Id, model.GetMillis()))
if result := <-ss.Command().GetByTrigger(o1.TeamId, o1.Trigger); result.Err == nil {
t.Fatal("no commands should have returned")
}
}
func TestCommandStoreDelete(t *testing.T) {
ss := Setup()
o1 := &model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger"
o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-ss.Command().Get(o1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.Command).CreateAt != o1.CreateAt {
t.Fatal("invalid returned command")
}
}
if r2 := <-ss.Command().Delete(o1.Id, model.GetMillis()); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Command().Get(o1.Id)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func TestCommandStoreDeleteByTeam(t *testing.T) {
ss := Setup()
o1 := &model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger"
o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-ss.Command().Get(o1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.Command).CreateAt != o1.CreateAt {
t.Fatal("invalid returned command")
}
}
if r2 := <-ss.Command().PermanentDeleteByTeam(o1.TeamId); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Command().Get(o1.Id)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func TestCommandStoreDeleteByUser(t *testing.T) {
ss := Setup()
o1 := &model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger"
o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-ss.Command().Get(o1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.Command).CreateAt != o1.CreateAt {
t.Fatal("invalid returned command")
}
}
if r2 := <-ss.Command().PermanentDeleteByUser(o1.CreatorId); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Command().Get(o1.Id)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func TestCommandStoreUpdate(t *testing.T) {
ss := Setup()
o1 := &model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger"
o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
o1.Token = model.NewId()
if r2 := <-ss.Command().Update(o1); r2.Err != nil {
t.Fatal(r2.Err)
}
}
func TestCommandCount(t *testing.T) {
ss := Setup()
o1 := &model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger"
o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-ss.Command().AnalyticsCommandCount(""); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(int64) == 0 {
t.Fatal("should be at least 1 command")
}
}
if r2 := <-ss.Command().AnalyticsCommandCount(o1.TeamId); r2.Err != nil {
t.Fatal(r2.Err)
} else {
if r2.Data.(int64) != 1 {
t.Fatal("should be 1 command")
}
}
func TestCommandStore(t *testing.T) {
StoreTest(t, storetest.TestCommandStore)
}

Просмотреть файл

@@ -1,4 +1,4 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package sqlstore
@@ -6,60 +6,9 @@ package sqlstore
import (
"testing"
"net/http"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestCommandWebhookStore(t *testing.T) {
ss := Setup()
cws := ss.CommandWebhook()
h1 := &model.CommandWebhook{}
h1.CommandId = model.NewId()
h1.UserId = model.NewId()
h1.ChannelId = model.NewId()
h1 = (<-cws.Save(h1)).Data.(*model.CommandWebhook)
if r1 := <-cws.Get(h1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if *r1.Data.(*model.CommandWebhook) != *h1 {
t.Fatal("invalid returned webhook")
}
}
if err := (<-cws.Get("123")).Err; err.StatusCode != http.StatusNotFound {
t.Fatal("Should have set the status as not found for missing id")
}
h2 := &model.CommandWebhook{}
h2.CreateAt = model.GetMillis() - 2*model.COMMAND_WEBHOOK_LIFETIME
h2.CommandId = model.NewId()
h2.UserId = model.NewId()
h2.ChannelId = model.NewId()
h2 = (<-cws.Save(h2)).Data.(*model.CommandWebhook)
if err := (<-cws.Get(h2.Id)).Err; err == nil || err.StatusCode != http.StatusNotFound {
t.Fatal("Should have set the status as not found for expired webhook")
}
cws.Cleanup()
if err := (<-cws.Get(h1.Id)).Err; err != nil {
t.Fatal("Should have no error getting unexpired webhook")
}
if err := (<-cws.Get(h2.Id)).Err; err.StatusCode != http.StatusNotFound {
t.Fatal("Should have set the status as not found for expired webhook")
}
if err := (<-cws.TryUse(h1.Id, 1)).Err; err != nil {
t.Fatal("Should be able to use webhook once")
}
if err := (<-cws.TryUse(h1.Id, 1)).Err; err == nil || err.StatusCode != http.StatusBadRequest {
t.Fatal("Should be able to use webhook once")
}
StoreTest(t, storetest.TestCommandWebhookStore)
}

Просмотреть файл

@@ -5,314 +5,10 @@ package sqlstore
import (
"testing"
"time"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestSqlComplianceStore(t *testing.T) {
ss := Setup()
compliance1 := &model.Compliance{Desc: "Audit for federal subpoena case #22443", UserId: model.NewId(), Status: model.COMPLIANCE_STATUS_FAILED, StartAt: model.GetMillis() - 1, EndAt: model.GetMillis() + 1, Type: model.COMPLIANCE_TYPE_ADHOC}
store.Must(ss.Compliance().Save(compliance1))
time.Sleep(100 * time.Millisecond)
compliance2 := &model.Compliance{Desc: "Audit for federal subpoena case #11458", UserId: model.NewId(), Status: model.COMPLIANCE_STATUS_RUNNING, StartAt: model.GetMillis() - 1, EndAt: model.GetMillis() + 1, Type: model.COMPLIANCE_TYPE_ADHOC}
store.Must(ss.Compliance().Save(compliance2))
time.Sleep(100 * time.Millisecond)
c := ss.Compliance().GetAll(0, 1000)
result := <-c
compliances := result.Data.(model.Compliances)
if compliances[0].Status != model.COMPLIANCE_STATUS_RUNNING && compliance2.Id != compliances[0].Id {
t.Fatal()
}
compliance2.Status = model.COMPLIANCE_STATUS_FAILED
store.Must(ss.Compliance().Update(compliance2))
c = ss.Compliance().GetAll(0, 1000)
result = <-c
compliances = result.Data.(model.Compliances)
if compliances[0].Status != model.COMPLIANCE_STATUS_FAILED && compliance2.Id != compliances[0].Id {
t.Fatal()
}
c = ss.Compliance().GetAll(0, 1)
result = <-c
compliances = result.Data.(model.Compliances)
if len(compliances) != 1 {
t.Fatal("should only have returned 1")
}
c = ss.Compliance().GetAll(1, 1)
result = <-c
compliances = result.Data.(model.Compliances)
if len(compliances) != 1 {
t.Fatal("should only have returned 1")
}
rc2 := (<-ss.Compliance().Get(compliance2.Id)).Data.(*model.Compliance)
if rc2.Status != compliance2.Status {
t.Fatal()
}
}
func TestComplianceExport(t *testing.T) {
ss := Setup()
time.Sleep(100 * time.Millisecond)
t1 := &model.Team{}
t1.DisplayName = "DisplayName"
t1.Name = "zz" + model.NewId() + "b"
t1.Email = model.NewId() + "@nowhere.com"
t1.Type = model.TEAM_OPEN
t1 = store.Must(ss.Team().Save(t1)).(*model.Team)
u1 := &model.User{}
u1.Email = model.NewId()
u1.Username = model.NewId()
u1 = store.Must(ss.User().Save(u1)).(*model.User)
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: t1.Id, UserId: u1.Id}))
u2 := &model.User{}
u2.Email = model.NewId()
u2.Username = model.NewId()
u2 = store.Must(ss.User().Save(u2)).(*model.User)
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: t1.Id, UserId: u2.Id}))
c1 := &model.Channel{}
c1.TeamId = t1.Id
c1.DisplayName = "Channel2"
c1.Name = "zz" + model.NewId() + "b"
c1.Type = model.CHANNEL_OPEN
c1 = store.Must(ss.Channel().Save(c1)).(*model.Channel)
o1 := &model.Post{}
o1.ChannelId = c1.Id
o1.UserId = u1.Id
o1.CreateAt = model.GetMillis()
o1.Message = "zz" + model.NewId() + "b"
o1 = store.Must(ss.Post().Save(o1)).(*model.Post)
o1a := &model.Post{}
o1a.ChannelId = c1.Id
o1a.UserId = u1.Id
o1a.CreateAt = o1.CreateAt + 10
o1a.Message = "zz" + model.NewId() + "b"
o1a = store.Must(ss.Post().Save(o1a)).(*model.Post)
o2 := &model.Post{}
o2.ChannelId = c1.Id
o2.UserId = u1.Id
o2.CreateAt = o1.CreateAt + 20
o2.Message = "zz" + model.NewId() + "b"
o2 = store.Must(ss.Post().Save(o2)).(*model.Post)
o2a := &model.Post{}
o2a.ChannelId = c1.Id
o2a.UserId = u2.Id
o2a.CreateAt = o1.CreateAt + 30
o2a.Message = "zz" + model.NewId() + "b"
o2a = store.Must(ss.Post().Save(o2a)).(*model.Post)
time.Sleep(100 * time.Millisecond)
cr1 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1}
if r1 := <-ss.Compliance().ComplianceExport(cr1); r1.Err != nil {
t.Fatal(r1.Err)
} else {
cposts := r1.Data.([]*model.CompliancePost)
if len(cposts) != 4 {
t.Fatal("return wrong results length")
}
if cposts[0].PostId != o1.Id {
t.Fatal("Wrong sort")
}
if cposts[3].PostId != o2a.Id {
t.Fatal("Wrong sort")
}
}
cr2 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Emails: u2.Email}
if r1 := <-ss.Compliance().ComplianceExport(cr2); r1.Err != nil {
t.Fatal(r1.Err)
} else {
cposts := r1.Data.([]*model.CompliancePost)
if len(cposts) != 1 {
t.Fatal("return wrong results length")
}
if cposts[0].PostId != o2a.Id {
t.Fatal("Wrong sort")
}
}
cr3 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Emails: u2.Email + ", " + u1.Email}
if r1 := <-ss.Compliance().ComplianceExport(cr3); r1.Err != nil {
t.Fatal(r1.Err)
} else {
cposts := r1.Data.([]*model.CompliancePost)
if len(cposts) != 4 {
t.Fatal("return wrong results length")
}
if cposts[0].PostId != o1.Id {
t.Fatal("Wrong sort")
}
if cposts[3].PostId != o2a.Id {
t.Fatal("Wrong sort")
}
}
cr4 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Keywords: o2a.Message}
if r1 := <-ss.Compliance().ComplianceExport(cr4); r1.Err != nil {
t.Fatal(r1.Err)
} else {
cposts := r1.Data.([]*model.CompliancePost)
if len(cposts) != 1 {
t.Fatal("return wrong results length")
}
if cposts[0].PostId != o2a.Id {
t.Fatal("Wrong sort")
}
}
cr5 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Keywords: o2a.Message + " " + o1.Message}
if r1 := <-ss.Compliance().ComplianceExport(cr5); r1.Err != nil {
t.Fatal(r1.Err)
} else {
cposts := r1.Data.([]*model.CompliancePost)
if len(cposts) != 2 {
t.Fatal("return wrong results length")
}
if cposts[0].PostId != o1.Id {
t.Fatal("Wrong sort")
}
}
cr6 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Emails: u2.Email + ", " + u1.Email, Keywords: o2a.Message + " " + o1.Message}
if r1 := <-ss.Compliance().ComplianceExport(cr6); r1.Err != nil {
t.Fatal(r1.Err)
} else {
cposts := r1.Data.([]*model.CompliancePost)
if len(cposts) != 2 {
t.Fatal("return wrong results length")
}
if cposts[0].PostId != o1.Id {
t.Fatal("Wrong sort")
}
if cposts[1].PostId != o2a.Id {
t.Fatal("Wrong sort")
}
}
}
func TestComplianceExportDirectMessages(t *testing.T) {
ss := Setup()
time.Sleep(100 * time.Millisecond)
t1 := &model.Team{}
t1.DisplayName = "DisplayName"
t1.Name = "zz" + model.NewId() + "b"
t1.Email = model.NewId() + "@nowhere.com"
t1.Type = model.TEAM_OPEN
t1 = store.Must(ss.Team().Save(t1)).(*model.Team)
u1 := &model.User{}
u1.Email = model.NewId()
u1.Username = model.NewId()
u1 = store.Must(ss.User().Save(u1)).(*model.User)
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: t1.Id, UserId: u1.Id}))
u2 := &model.User{}
u2.Email = model.NewId()
u2.Username = model.NewId()
u2 = store.Must(ss.User().Save(u2)).(*model.User)
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: t1.Id, UserId: u2.Id}))
c1 := &model.Channel{}
c1.TeamId = t1.Id
c1.DisplayName = "Channel2"
c1.Name = "zz" + model.NewId() + "b"
c1.Type = model.CHANNEL_OPEN
c1 = store.Must(ss.Channel().Save(c1)).(*model.Channel)
cDM := store.Must(ss.Channel().CreateDirectChannel(u1.Id, u2.Id)).(*model.Channel)
o1 := &model.Post{}
o1.ChannelId = c1.Id
o1.UserId = u1.Id
o1.CreateAt = model.GetMillis()
o1.Message = "zz" + model.NewId() + "b"
o1 = store.Must(ss.Post().Save(o1)).(*model.Post)
o1a := &model.Post{}
o1a.ChannelId = c1.Id
o1a.UserId = u1.Id
o1a.CreateAt = o1.CreateAt + 10
o1a.Message = "zz" + model.NewId() + "b"
o1a = store.Must(ss.Post().Save(o1a)).(*model.Post)
o2 := &model.Post{}
o2.ChannelId = c1.Id
o2.UserId = u1.Id
o2.CreateAt = o1.CreateAt + 20
o2.Message = "zz" + model.NewId() + "b"
o2 = store.Must(ss.Post().Save(o2)).(*model.Post)
o2a := &model.Post{}
o2a.ChannelId = c1.Id
o2a.UserId = u2.Id
o2a.CreateAt = o1.CreateAt + 30
o2a.Message = "zz" + model.NewId() + "b"
o2a = store.Must(ss.Post().Save(o2a)).(*model.Post)
o3 := &model.Post{}
o3.ChannelId = cDM.Id
o3.UserId = u1.Id
o3.CreateAt = o1.CreateAt + 40
o3.Message = "zz" + model.NewId() + "b"
o3 = store.Must(ss.Post().Save(o3)).(*model.Post)
time.Sleep(100 * time.Millisecond)
cr1 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o3.CreateAt + 1, Emails: u1.Email}
if r1 := <-ss.Compliance().ComplianceExport(cr1); r1.Err != nil {
t.Fatal(r1.Err)
} else {
cposts := r1.Data.([]*model.CompliancePost)
if len(cposts) != 4 {
t.Fatal("return wrong results length")
}
if cposts[0].PostId != o1.Id {
t.Fatal("Wrong sort")
}
if cposts[len(cposts)-1].PostId != o3.Id {
t.Fatal("Wrong sort")
}
}
func TestComplianceStore(t *testing.T) {
StoreTest(t, storetest.TestComplianceStore)
}

Просмотреть файл

@@ -1,176 +1,14 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package sqlstore
import (
"testing"
"time"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestEmojiSaveDelete(t *testing.T) {
ss := Setup()
emoji1 := &model.Emoji{
CreatorId: model.NewId(),
Name: model.NewId(),
}
if result := <-ss.Emoji().Save(emoji1); result.Err != nil {
t.Fatal(result.Err)
}
if len(emoji1.Id) != 26 {
t.Fatal("should've set id for emoji")
}
emoji2 := model.Emoji{
CreatorId: model.NewId(),
Name: emoji1.Name,
}
if result := <-ss.Emoji().Save(&emoji2); result.Err == nil {
t.Fatal("shouldn't be able to save emoji with duplicate name")
}
if result := <-ss.Emoji().Delete(emoji1.Id, time.Now().Unix()); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.Emoji().Save(&emoji2); result.Err != nil {
t.Fatal("should be able to save emoji with duplicate name now that original has been deleted", result.Err)
}
if result := <-ss.Emoji().Delete(emoji2.Id, time.Now().Unix()+1); result.Err != nil {
t.Fatal(result.Err)
}
}
func TestEmojiGet(t *testing.T) {
ss := Setup()
emojis := []model.Emoji{
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
}
for i, emoji := range emojis {
emojis[i] = *store.Must(ss.Emoji().Save(&emoji)).(*model.Emoji)
}
defer func() {
for _, emoji := range emojis {
store.Must(ss.Emoji().Delete(emoji.Id, time.Now().Unix()))
}
}()
for _, emoji := range emojis {
if result := <-ss.Emoji().Get(emoji.Id, false); result.Err != nil {
t.Fatalf("failed to get emoji with id %v: %v", emoji.Id, result.Err)
}
}
for _, emoji := range emojis {
if result := <-ss.Emoji().Get(emoji.Id, true); result.Err != nil {
t.Fatalf("failed to get emoji with id %v: %v", emoji.Id, result.Err)
}
}
for _, emoji := range emojis {
if result := <-ss.Emoji().Get(emoji.Id, true); result.Err != nil {
t.Fatalf("failed to get emoji with id %v: %v", emoji.Id, result.Err)
}
}
}
func TestEmojiGetByName(t *testing.T) {
ss := Setup()
emojis := []model.Emoji{
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
}
for i, emoji := range emojis {
emojis[i] = *store.Must(ss.Emoji().Save(&emoji)).(*model.Emoji)
}
defer func() {
for _, emoji := range emojis {
store.Must(ss.Emoji().Delete(emoji.Id, time.Now().Unix()))
}
}()
for _, emoji := range emojis {
if result := <-ss.Emoji().GetByName(emoji.Name); result.Err != nil {
t.Fatalf("failed to get emoji with name %v: %v", emoji.Name, result.Err)
}
}
}
func TestEmojiGetList(t *testing.T) {
ss := Setup()
emojis := []model.Emoji{
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
}
for i, emoji := range emojis {
emojis[i] = *store.Must(ss.Emoji().Save(&emoji)).(*model.Emoji)
}
defer func() {
for _, emoji := range emojis {
store.Must(ss.Emoji().Delete(emoji.Id, time.Now().Unix()))
}
}()
if result := <-ss.Emoji().GetList(0, 100); result.Err != nil {
t.Fatal(result.Err)
} else {
for _, emoji := range emojis {
found := false
for _, savedEmoji := range result.Data.([]*model.Emoji) {
if emoji.Id == savedEmoji.Id {
found = true
break
}
}
if !found {
t.Fatalf("failed to get emoji with id %v", emoji.Id)
}
}
}
func TestEmojiStore(t *testing.T) {
StoreTest(t, storetest.TestEmojiStore)
}

Просмотреть файл

@@ -1,300 +1,14 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package sqlstore
import (
"fmt"
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestFileInfoSaveGet(t *testing.T) {
ss := Setup()
info := &model.FileInfo{
CreatorId: model.NewId(),
Path: "file.txt",
}
if result := <-ss.FileInfo().Save(info); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.(*model.FileInfo); len(returned.Id) == 0 {
t.Fatal("should've assigned an id to FileInfo")
} else {
info = returned
}
defer func() {
<-ss.FileInfo().PermanentDelete(info.Id)
}()
if result := <-ss.FileInfo().Get(info.Id); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.(*model.FileInfo); returned.Id != info.Id {
t.Log(info)
t.Log(returned)
t.Fatal("should've returned correct FileInfo")
}
info2 := store.Must(ss.FileInfo().Save(&model.FileInfo{
CreatorId: model.NewId(),
Path: "file.txt",
DeleteAt: 123,
})).(*model.FileInfo)
if result := <-ss.FileInfo().Get(info2.Id); result.Err == nil {
t.Fatal("shouldn't have gotten deleted file")
}
defer func() {
<-ss.FileInfo().PermanentDelete(info2.Id)
}()
}
func TestFileInfoSaveGetByPath(t *testing.T) {
ss := Setup()
info := &model.FileInfo{
CreatorId: model.NewId(),
Path: fmt.Sprintf("%v/file.txt", model.NewId()),
}
if result := <-ss.FileInfo().Save(info); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.(*model.FileInfo); len(returned.Id) == 0 {
t.Fatal("should've assigned an id to FileInfo")
} else {
info = returned
}
defer func() {
<-ss.FileInfo().PermanentDelete(info.Id)
}()
if result := <-ss.FileInfo().GetByPath(info.Path); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.(*model.FileInfo); returned.Id != info.Id {
t.Log(info)
t.Log(returned)
t.Fatal("should've returned correct FileInfo")
}
info2 := store.Must(ss.FileInfo().Save(&model.FileInfo{
CreatorId: model.NewId(),
Path: "file.txt",
DeleteAt: 123,
})).(*model.FileInfo)
if result := <-ss.FileInfo().GetByPath(info2.Id); result.Err == nil {
t.Fatal("shouldn't have gotten deleted file")
}
defer func() {
<-ss.FileInfo().PermanentDelete(info2.Id)
}()
}
func TestFileInfoGetForPost(t *testing.T) {
ss := Setup()
userId := model.NewId()
postId := model.NewId()
infos := []*model.FileInfo{
{
PostId: postId,
CreatorId: userId,
Path: "file.txt",
},
{
PostId: postId,
CreatorId: userId,
Path: "file.txt",
},
{
PostId: postId,
CreatorId: userId,
Path: "file.txt",
DeleteAt: 123,
},
{
PostId: model.NewId(),
CreatorId: userId,
Path: "file.txt",
},
}
for i, info := range infos {
infos[i] = store.Must(ss.FileInfo().Save(info)).(*model.FileInfo)
defer func(id string) {
<-ss.FileInfo().PermanentDelete(id)
}(infos[i].Id)
}
if result := <-ss.FileInfo().GetForPost(postId, true, false); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.([]*model.FileInfo); len(returned) != 2 {
t.Fatal("should've returned exactly 2 file infos")
}
if result := <-ss.FileInfo().GetForPost(postId, false, false); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.([]*model.FileInfo); len(returned) != 2 {
t.Fatal("should've returned exactly 2 file infos")
}
if result := <-ss.FileInfo().GetForPost(postId, true, true); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.([]*model.FileInfo); len(returned) != 2 {
t.Fatal("should've returned exactly 2 file infos")
}
}
func TestFileInfoAttachToPost(t *testing.T) {
ss := Setup()
userId := model.NewId()
postId := model.NewId()
info1 := store.Must(ss.FileInfo().Save(&model.FileInfo{
CreatorId: userId,
Path: "file.txt",
})).(*model.FileInfo)
defer func() {
<-ss.FileInfo().PermanentDelete(info1.Id)
}()
if len(info1.PostId) != 0 {
t.Fatal("file shouldn't have a PostId")
}
if result := <-ss.FileInfo().AttachToPost(info1.Id, postId); result.Err != nil {
t.Fatal(result.Err)
} else {
info1 = store.Must(ss.FileInfo().Get(info1.Id)).(*model.FileInfo)
}
if len(info1.PostId) == 0 {
t.Fatal("file should now have a PostId")
}
info2 := store.Must(ss.FileInfo().Save(&model.FileInfo{
CreatorId: userId,
Path: "file.txt",
})).(*model.FileInfo)
defer func() {
<-ss.FileInfo().PermanentDelete(info2.Id)
}()
if result := <-ss.FileInfo().AttachToPost(info2.Id, postId); result.Err != nil {
t.Fatal(result.Err)
} else {
info2 = store.Must(ss.FileInfo().Get(info2.Id)).(*model.FileInfo)
}
if result := <-ss.FileInfo().GetForPost(postId, true, false); result.Err != nil {
t.Fatal(result.Err)
} else if infos := result.Data.([]*model.FileInfo); len(infos) != 2 {
t.Fatal("should've returned exactly 2 file infos")
}
}
func TestFileInfoDeleteForPost(t *testing.T) {
ss := Setup()
userId := model.NewId()
postId := model.NewId()
infos := []*model.FileInfo{
{
PostId: postId,
CreatorId: userId,
Path: "file.txt",
},
{
PostId: postId,
CreatorId: userId,
Path: "file.txt",
},
{
PostId: postId,
CreatorId: userId,
Path: "file.txt",
DeleteAt: 123,
},
{
PostId: model.NewId(),
CreatorId: userId,
Path: "file.txt",
},
}
for i, info := range infos {
infos[i] = store.Must(ss.FileInfo().Save(info)).(*model.FileInfo)
defer func(id string) {
<-ss.FileInfo().PermanentDelete(id)
}(infos[i].Id)
}
if result := <-ss.FileInfo().DeleteForPost(postId); result.Err != nil {
t.Fatal(result.Err)
}
if infos := store.Must(ss.FileInfo().GetForPost(postId, true, false)).([]*model.FileInfo); len(infos) != 0 {
t.Fatal("shouldn't have returned any file infos")
}
}
func TestFileInfoPermanentDelete(t *testing.T) {
ss := Setup()
info := store.Must(ss.FileInfo().Save(&model.FileInfo{
PostId: model.NewId(),
CreatorId: model.NewId(),
Path: "file.txt",
})).(*model.FileInfo)
if result := <-ss.FileInfo().PermanentDelete(info.Id); result.Err != nil {
t.Fatal(result.Err)
}
}
func TestFileInfoPermanentDeleteBatch(t *testing.T) {
ss := Setup()
postId := model.NewId()
store.Must(ss.FileInfo().Save(&model.FileInfo{
PostId: postId,
CreatorId: model.NewId(),
Path: "file.txt",
CreateAt: 1000,
}))
store.Must(ss.FileInfo().Save(&model.FileInfo{
PostId: postId,
CreatorId: model.NewId(),
Path: "file.txt",
CreateAt: 1200,
}))
store.Must(ss.FileInfo().Save(&model.FileInfo{
PostId: postId,
CreatorId: model.NewId(),
Path: "file.txt",
CreateAt: 2000,
}))
if result := <-ss.FileInfo().GetForPost(postId, true, false); result.Err != nil {
t.Fatal(result.Err)
} else if len(result.Data.([]*model.FileInfo)) != 3 {
t.Fatal("Expected 3 fileInfos")
}
store.Must(ss.FileInfo().PermanentDeleteBatch(1500, 1000))
if result := <-ss.FileInfo().GetForPost(postId, true, false); result.Err != nil {
t.Fatal(result.Err)
} else if len(result.Data.([]*model.FileInfo)) != 1 {
t.Fatal("Expected 3 fileInfos")
}
func TestFileInfoStore(t *testing.T) {
StoreTest(t, storetest.TestFileInfoStore)
}

Просмотреть файл

@@ -1,4 +1,4 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package sqlstore
@@ -6,509 +6,9 @@ package sqlstore
import (
"testing"
"time"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/stretchr/testify/assert"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestJobSaveGet(t *testing.T) {
ss := Setup()
job := &model.Job{
Id: model.NewId(),
Type: model.NewId(),
Status: model.NewId(),
Data: map[string]string{
"Processed": "0",
"Total": "12345",
"LastProcessed": "abcd",
},
}
if result := <-ss.Job().Save(job); result.Err != nil {
t.Fatal(result.Err)
}
defer func() {
<-ss.Job().Delete(job.Id)
}()
if result := <-ss.Job().Get(job.Id); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.(*model.Job); received.Id != job.Id {
t.Fatal("received incorrect job after save")
} else if received.Data["Total"] != "12345" {
t.Fatal("data field was not retrieved successfully:", received.Data)
}
}
func TestJobGetAllByType(t *testing.T) {
ss := Setup()
jobType := model.NewId()
jobs := []*model.Job{
{
Id: model.NewId(),
Type: jobType,
},
{
Id: model.NewId(),
Type: jobType,
},
{
Id: model.NewId(),
Type: model.NewId(),
},
}
for _, job := range jobs {
store.Must(ss.Job().Save(job))
defer ss.Job().Delete(job.Id)
}
if result := <-ss.Job().GetAllByType(jobType); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) != 2 {
t.Fatal("received wrong number of jobs")
} else if received[0].Id != jobs[0].Id && received[1].Id != jobs[0].Id {
t.Fatal("should've received first jobs")
} else if received[0].Id != jobs[1].Id && received[1].Id != jobs[1].Id {
t.Fatal("should've received second jobs")
}
}
func TestJobGetAllByTypePage(t *testing.T) {
ss := Setup()
jobType := model.NewId()
jobs := []*model.Job{
{
Id: model.NewId(),
Type: jobType,
CreateAt: 1000,
},
{
Id: model.NewId(),
Type: jobType,
CreateAt: 999,
},
{
Id: model.NewId(),
Type: jobType,
CreateAt: 1001,
},
{
Id: model.NewId(),
Type: model.NewId(),
CreateAt: 1002,
},
}
for _, job := range jobs {
store.Must(ss.Job().Save(job))
defer ss.Job().Delete(job.Id)
}
if result := <-ss.Job().GetAllByTypePage(jobType, 0, 2); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) != 2 {
t.Fatal("received wrong number of jobs")
} else if received[0].Id != jobs[2].Id {
t.Fatal("should've received newest job first")
} else if received[1].Id != jobs[0].Id {
t.Fatal("should've received second newest job second")
}
if result := <-ss.Job().GetAllByTypePage(jobType, 2, 2); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) != 1 {
t.Fatal("received wrong number of jobs")
} else if received[0].Id != jobs[1].Id {
t.Fatal("should've received oldest job last")
}
}
func TestJobGetAllPage(t *testing.T) {
ss := Setup()
jobType := model.NewId()
createAtTime := model.GetMillis()
jobs := []*model.Job{
{
Id: model.NewId(),
Type: jobType,
CreateAt: createAtTime + 1,
},
{
Id: model.NewId(),
Type: jobType,
CreateAt: createAtTime,
},
{
Id: model.NewId(),
Type: jobType,
CreateAt: createAtTime + 2,
},
}
for _, job := range jobs {
store.Must(ss.Job().Save(job))
defer ss.Job().Delete(job.Id)
}
if result := <-ss.Job().GetAllPage(0, 2); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) != 2 {
t.Fatal("received wrong number of jobs")
} else if received[0].Id != jobs[2].Id {
t.Fatal("should've received newest job first")
} else if received[1].Id != jobs[0].Id {
t.Fatal("should've received second newest job second")
}
if result := <-ss.Job().GetAllPage(2, 2); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) < 1 {
t.Fatal("received wrong number of jobs")
} else if received[0].Id != jobs[1].Id {
t.Fatal("should've received oldest job last")
}
}
func TestJobGetAllByStatus(t *testing.T) {
ss := Setup()
jobType := model.NewId()
status := model.NewId()
jobs := []*model.Job{
{
Id: model.NewId(),
Type: jobType,
CreateAt: 1000,
Status: status,
Data: map[string]string{
"test": "data",
},
},
{
Id: model.NewId(),
Type: jobType,
CreateAt: 999,
Status: status,
},
{
Id: model.NewId(),
Type: jobType,
CreateAt: 1001,
Status: status,
},
{
Id: model.NewId(),
Type: jobType,
CreateAt: 1002,
Status: model.NewId(),
},
}
for _, job := range jobs {
store.Must(ss.Job().Save(job))
defer ss.Job().Delete(job.Id)
}
if result := <-ss.Job().GetAllByStatus(status); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) != 3 {
t.Fatal("received wrong number of jobs")
} else if received[0].Id != jobs[1].Id || received[1].Id != jobs[0].Id || received[2].Id != jobs[2].Id {
t.Fatal("should've received jobs ordered by CreateAt time")
} else if received[1].Data["test"] != "data" {
t.Fatal("should've received job data field back as saved")
}
}
func TestJobStoreGetNewestJobByStatusAndType(t *testing.T) {
ss := Setup()
jobType1 := model.NewId()
jobType2 := model.NewId()
status1 := model.NewId()
status2 := model.NewId()
jobs := []*model.Job{
{
Id: model.NewId(),
Type: jobType1,
CreateAt: 1001,
Status: status1,
},
{
Id: model.NewId(),
Type: jobType1,
CreateAt: 1000,
Status: status1,
},
{
Id: model.NewId(),
Type: jobType2,
CreateAt: 1003,
Status: status1,
},
{
Id: model.NewId(),
Type: jobType1,
CreateAt: 1004,
Status: status2,
},
}
for _, job := range jobs {
store.Must(ss.Job().Save(job))
defer ss.Job().Delete(job.Id)
}
result := <-ss.Job().GetNewestJobByStatusAndType(status1, jobType1)
assert.Nil(t, result.Err)
assert.EqualValues(t, jobs[0].Id, result.Data.(*model.Job).Id)
result = <-ss.Job().GetNewestJobByStatusAndType(model.NewId(), model.NewId())
assert.Nil(t, result.Err)
assert.Nil(t, result.Data.(*model.Job))
}
func TestJobStoreGetCountByStatusAndType(t *testing.T) {
ss := Setup()
jobType1 := model.NewId()
jobType2 := model.NewId()
status1 := model.NewId()
status2 := model.NewId()
jobs := []*model.Job{
{
Id: model.NewId(),
Type: jobType1,
CreateAt: 1000,
Status: status1,
},
{
Id: model.NewId(),
Type: jobType1,
CreateAt: 999,
Status: status1,
},
{
Id: model.NewId(),
Type: jobType2,
CreateAt: 1001,
Status: status1,
},
{
Id: model.NewId(),
Type: jobType1,
CreateAt: 1002,
Status: status2,
},
}
for _, job := range jobs {
store.Must(ss.Job().Save(job))
defer ss.Job().Delete(job.Id)
}
result := <-ss.Job().GetCountByStatusAndType(status1, jobType1)
assert.Nil(t, result.Err)
assert.EqualValues(t, 2, result.Data.(int64))
result = <-ss.Job().GetCountByStatusAndType(status2, jobType2)
assert.Nil(t, result.Err)
assert.EqualValues(t, 0, result.Data.(int64))
result = <-ss.Job().GetCountByStatusAndType(status1, jobType2)
assert.Nil(t, result.Err)
assert.EqualValues(t, 1, result.Data.(int64))
result = <-ss.Job().GetCountByStatusAndType(status2, jobType1)
assert.Nil(t, result.Err)
assert.EqualValues(t, 1, result.Data.(int64))
}
func TestJobUpdateOptimistically(t *testing.T) {
ss := Setup()
job := &model.Job{
Id: model.NewId(),
Type: model.JOB_TYPE_DATA_RETENTION,
CreateAt: model.GetMillis(),
Status: model.JOB_STATUS_PENDING,
}
if result := <-ss.Job().Save(job); result.Err != nil {
t.Fatal(result.Err)
}
defer ss.Job().Delete(job.Id)
job.LastActivityAt = model.GetMillis()
job.Status = model.JOB_STATUS_IN_PROGRESS
job.Progress = 50
job.Data = map[string]string{
"Foo": "Bar",
}
if result := <-ss.Job().UpdateOptimistically(job, model.JOB_STATUS_SUCCESS); result.Err != nil {
if result.Data.(bool) {
t.Fatal("should have failed due to incorrect old status")
}
}
time.Sleep(2 * time.Millisecond)
if result := <-ss.Job().UpdateOptimistically(job, model.JOB_STATUS_PENDING); result.Err != nil {
t.Fatal(result.Err)
} else {
if !result.Data.(bool) {
t.Fatal("Should have successfully updated")
}
var updatedJob *model.Job
if result := <-ss.Job().Get(job.Id); result.Err != nil {
t.Fatal(result.Err)
} else {
updatedJob = result.Data.(*model.Job)
}
if updatedJob.Type != job.Type || updatedJob.CreateAt != job.CreateAt || updatedJob.Status != job.Status || updatedJob.LastActivityAt <= job.LastActivityAt || updatedJob.Progress != job.Progress || updatedJob.Data["Foo"] != job.Data["Foo"] {
t.Fatal("Some update property was not as expected")
}
}
}
func TestJobUpdateStatusUpdateStatusOptimistically(t *testing.T) {
ss := Setup()
job := &model.Job{
Id: model.NewId(),
Type: model.JOB_TYPE_DATA_RETENTION,
CreateAt: model.GetMillis(),
Status: model.JOB_STATUS_SUCCESS,
}
var lastUpdateAt int64
if result := <-ss.Job().Save(job); result.Err != nil {
t.Fatal(result.Err)
} else {
lastUpdateAt = result.Data.(*model.Job).LastActivityAt
}
defer ss.Job().Delete(job.Id)
time.Sleep(2 * time.Millisecond)
if result := <-ss.Job().UpdateStatus(job.Id, model.JOB_STATUS_PENDING); result.Err != nil {
t.Fatal(result.Err)
} else {
received := result.Data.(*model.Job)
if received.Status != model.JOB_STATUS_PENDING {
t.Fatal("status wasn't updated")
}
if received.LastActivityAt <= lastUpdateAt {
t.Fatal("lastActivityAt wasn't updated")
}
lastUpdateAt = received.LastActivityAt
}
time.Sleep(2 * time.Millisecond)
if result := <-ss.Job().UpdateStatusOptimistically(job.Id, model.JOB_STATUS_IN_PROGRESS, model.JOB_STATUS_SUCCESS); result.Err != nil {
t.Fatal(result.Err)
} else {
if result.Data.(bool) {
t.Fatal("should be false due to incorrect original status")
}
}
if result := <-ss.Job().Get(job.Id); result.Err != nil {
t.Fatal(result.Err)
} else {
received := result.Data.(*model.Job)
if received.Status != model.JOB_STATUS_PENDING {
t.Fatal("should still be pending")
}
if received.LastActivityAt != lastUpdateAt {
t.Fatal("last activity at shouldn't have changed")
}
}
time.Sleep(2 * time.Millisecond)
if result := <-ss.Job().UpdateStatusOptimistically(job.Id, model.JOB_STATUS_PENDING, model.JOB_STATUS_IN_PROGRESS); result.Err != nil {
t.Fatal(result.Err)
} else {
if !result.Data.(bool) {
t.Fatal("should have succeeded")
}
}
var startAtSet int64
if result := <-ss.Job().Get(job.Id); result.Err != nil {
t.Fatal(result.Err)
} else {
received := result.Data.(*model.Job)
if received.Status != model.JOB_STATUS_IN_PROGRESS {
t.Fatal("should be in progress")
}
if received.StartAt == 0 {
t.Fatal("received should have start at set")
}
if received.LastActivityAt <= lastUpdateAt {
t.Fatal("lastActivityAt wasn't updated")
}
lastUpdateAt = received.LastActivityAt
startAtSet = received.StartAt
}
time.Sleep(2 * time.Millisecond)
if result := <-ss.Job().UpdateStatusOptimistically(job.Id, model.JOB_STATUS_IN_PROGRESS, model.JOB_STATUS_SUCCESS); result.Err != nil {
t.Fatal(result.Err)
} else {
if !result.Data.(bool) {
t.Fatal("should have succeeded")
}
}
if result := <-ss.Job().Get(job.Id); result.Err != nil {
t.Fatal(result.Err)
} else {
received := result.Data.(*model.Job)
if received.Status != model.JOB_STATUS_SUCCESS {
t.Fatal("should be success status")
}
if received.StartAt != startAtSet {
t.Fatal("startAt should not have changed")
}
if received.LastActivityAt <= lastUpdateAt {
t.Fatal("lastActivityAt wasn't updated")
}
lastUpdateAt = received.LastActivityAt
}
}
func TestJobDelete(t *testing.T) {
ss := Setup()
job := store.Must(ss.Job().Save(&model.Job{
Id: model.NewId(),
})).(*model.Job)
if result := <-ss.Job().Delete(job.Id); result.Err != nil {
t.Fatal(result.Err)
}
func TestJobStore(t *testing.T) {
StoreTest(t, storetest.TestJobStore)
}

Просмотреть файл

@@ -1,4 +1,4 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package sqlstore
@@ -6,50 +6,9 @@ package sqlstore
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestLicenseStoreSave(t *testing.T) {
ss := Setup()
l1 := model.LicenseRecord{}
l1.Id = model.NewId()
l1.Bytes = "junk"
if err := (<-ss.License().Save(&l1)).Err; err != nil {
t.Fatal("couldn't save license record", err)
}
if err := (<-ss.License().Save(&l1)).Err; err != nil {
t.Fatal("shouldn't fail on trying to save existing license record", err)
}
l1.Id = ""
if err := (<-ss.License().Save(&l1)).Err; err == nil {
t.Fatal("should fail on invalid license", err)
}
}
func TestLicenseStoreGet(t *testing.T) {
ss := Setup()
l1 := model.LicenseRecord{}
l1.Id = model.NewId()
l1.Bytes = "junk"
store.Must(ss.License().Save(&l1))
if r := <-ss.License().Get(l1.Id); r.Err != nil {
t.Fatal("couldn't get license", r.Err)
} else {
if r.Data.(*model.LicenseRecord).Bytes != l1.Bytes {
t.Fatal("license bytes didn't match")
}
}
if err := (<-ss.License().Get("missing")).Err; err == nil {
t.Fatal("should fail on get license", err)
}
func TestLicenseStore(t *testing.T) {
StoreTest(t, storetest.TestLicenseStore)
}

Просмотреть файл

@@ -6,441 +6,9 @@ package sqlstore
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestOAuthStoreSaveApp(t *testing.T) {
ss := Setup()
a1 := model.OAuthApp{}
a1.CreatorId = model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com"
// Try to save an app that already has an Id
a1.Id = model.NewId()
if err := (<-ss.OAuth().SaveApp(&a1)).Err; err == nil {
t.Fatal("Should have failed, cannot add an OAuth app cannot be save with an Id, it has to be updated")
}
// Try to save an Invalid App
a1.Id = ""
if err := (<-ss.OAuth().SaveApp(&a1)).Err; err == nil {
t.Fatal("Should have failed, app should be invalid cause it doesn' have a name set")
}
// Save the app
a1.Id = ""
a1.Name = "TestApp" + model.NewId()
if err := (<-ss.OAuth().SaveApp(&a1)).Err; err != nil {
t.Fatal(err)
}
}
func TestOAuthStoreGetApp(t *testing.T) {
ss := Setup()
a1 := model.OAuthApp{}
a1.CreatorId = model.NewId()
a1.Name = "TestApp" + model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com"
store.Must(ss.OAuth().SaveApp(&a1))
// Lets try to get and app that does not exists
if err := (<-ss.OAuth().GetApp("fake0123456789abcderfgret1")).Err; err == nil {
t.Fatal("Should have failed. App does not exists")
}
if err := (<-ss.OAuth().GetApp(a1.Id)).Err; err != nil {
t.Fatal(err)
}
// Lets try and get the app from a user that hasn't created any apps
if result := (<-ss.OAuth().GetAppByUser("fake0123456789abcderfgret1", 0, 1000)); result.Err == nil {
if len(result.Data.([]*model.OAuthApp)) > 0 {
t.Fatal("Should have failed. Fake user hasn't created any apps")
}
} else {
t.Fatal(result.Err)
}
if err := (<-ss.OAuth().GetAppByUser(a1.CreatorId, 0, 1000)).Err; err != nil {
t.Fatal(err)
}
if err := (<-ss.OAuth().GetApps(0, 1000)).Err; err != nil {
t.Fatal(err)
}
}
func TestOAuthStoreUpdateApp(t *testing.T) {
ss := Setup()
a1 := model.OAuthApp{}
a1.CreatorId = model.NewId()
a1.Name = "TestApp" + model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com"
store.Must(ss.OAuth().SaveApp(&a1))
// temporarily save the created app id
id := a1.Id
a1.CreateAt = 1
a1.ClientSecret = "pwd"
a1.CreatorId = "12345678901234567890123456"
// Lets update the app by removing the name
a1.Name = ""
if result := <-ss.OAuth().UpdateApp(&a1); result.Err == nil {
t.Fatal("Should have failed. App name is not set")
}
// Lets not find the app that we are trying to update
a1.Id = "fake0123456789abcderfgret1"
a1.Name = "NewName"
if result := <-ss.OAuth().UpdateApp(&a1); result.Err == nil {
t.Fatal("Should have failed. Not able to find the app")
}
a1.Id = id
if result := <-ss.OAuth().UpdateApp(&a1); result.Err != nil {
t.Fatal(result.Err)
} else {
ua1 := (result.Data.([2]*model.OAuthApp)[0])
if ua1.Name != "NewName" {
t.Fatal("name did not update")
}
if ua1.CreateAt == 1 {
t.Fatal("create at should not have updated")
}
if ua1.CreatorId == "12345678901234567890123456" {
t.Fatal("creator id should not have updated")
}
}
}
func TestOAuthStoreSaveAccessData(t *testing.T) {
ss := Setup()
a1 := model.AccessData{}
a1.ClientId = model.NewId()
a1.UserId = model.NewId()
// Lets try and save an incomplete access data
if err := (<-ss.OAuth().SaveAccessData(&a1)).Err; err == nil {
t.Fatal("Should have failed. Access data needs the token")
}
a1.Token = model.NewId()
a1.RefreshToken = model.NewId()
a1.RedirectUri = "http://example.com"
if err := (<-ss.OAuth().SaveAccessData(&a1)).Err; err != nil {
t.Fatal(err)
}
}
func TestOAuthUpdateAccessData(t *testing.T) {
ss := Setup()
a1 := model.AccessData{}
a1.ClientId = model.NewId()
a1.UserId = model.NewId()
a1.Token = model.NewId()
a1.RefreshToken = model.NewId()
a1.ExpiresAt = model.GetMillis()
a1.RedirectUri = "http://example.com"
store.Must(ss.OAuth().SaveAccessData(&a1))
//Try to update to invalid Refresh Token
refreshToken := a1.RefreshToken
a1.RefreshToken = model.NewId() + "123"
if err := (<-ss.OAuth().UpdateAccessData(&a1)).Err; err == nil {
t.Fatal("Should have failed with invalid token")
}
//Try to update to invalid RedirectUri
a1.RefreshToken = model.NewId()
a1.RedirectUri = ""
if err := (<-ss.OAuth().UpdateAccessData(&a1)).Err; err == nil {
t.Fatal("Should have failed with invalid Redirect URI")
}
// Should update fine
a1.RedirectUri = "http://example.com"
if result := <-ss.OAuth().UpdateAccessData(&a1); result.Err != nil {
t.Fatal(result.Err)
} else {
ra1 := result.Data.(*model.AccessData)
if ra1.RefreshToken == refreshToken {
t.Fatal("refresh tokens didn't match")
}
}
}
func TestOAuthStoreGetAccessData(t *testing.T) {
ss := Setup()
a1 := model.AccessData{}
a1.ClientId = model.NewId()
a1.UserId = model.NewId()
a1.Token = model.NewId()
a1.RefreshToken = model.NewId()
a1.ExpiresAt = model.GetMillis()
a1.RedirectUri = "http://example.com"
store.Must(ss.OAuth().SaveAccessData(&a1))
if err := (<-ss.OAuth().GetAccessData("invalidToken")).Err; err == nil {
t.Fatal("Should have failed. There is no data with an invalid token")
}
if result := <-ss.OAuth().GetAccessData(a1.Token); result.Err != nil {
t.Fatal(result.Err)
} else {
ra1 := result.Data.(*model.AccessData)
if a1.Token != ra1.Token {
t.Fatal("tokens didn't match")
}
}
if err := (<-ss.OAuth().GetPreviousAccessData(a1.UserId, a1.ClientId)).Err; err != nil {
t.Fatal(err)
}
if err := (<-ss.OAuth().GetPreviousAccessData("user", "junk")).Err; err != nil {
t.Fatal(err)
}
// Try to get the Access data using an invalid refresh token
if err := (<-ss.OAuth().GetAccessDataByRefreshToken(a1.Token)).Err; err == nil {
t.Fatal("Should have failed. There is no data with an invalid token")
}
// Get the Access Data using the refresh token
if result := <-ss.OAuth().GetAccessDataByRefreshToken(a1.RefreshToken); result.Err != nil {
t.Fatal(result.Err)
} else {
ra1 := result.Data.(*model.AccessData)
if a1.RefreshToken != ra1.RefreshToken {
t.Fatal("tokens didn't match")
}
}
}
func TestOAuthStoreRemoveAccessData(t *testing.T) {
ss := Setup()
a1 := model.AccessData{}
a1.ClientId = model.NewId()
a1.UserId = model.NewId()
a1.Token = model.NewId()
a1.RefreshToken = model.NewId()
a1.RedirectUri = "http://example.com"
store.Must(ss.OAuth().SaveAccessData(&a1))
if err := (<-ss.OAuth().RemoveAccessData(a1.Token)).Err; err != nil {
t.Fatal(err)
}
if result := (<-ss.OAuth().GetPreviousAccessData(a1.UserId, a1.ClientId)); result.Err != nil {
} else {
if result.Data != nil {
t.Fatal("did not delete access token")
}
}
}
func TestOAuthStoreSaveAuthData(t *testing.T) {
ss := Setup()
a1 := model.AuthData{}
a1.ClientId = model.NewId()
a1.UserId = model.NewId()
a1.Code = model.NewId()
a1.RedirectUri = "http://example.com"
if err := (<-ss.OAuth().SaveAuthData(&a1)).Err; err != nil {
t.Fatal(err)
}
}
func TestOAuthStoreGetAuthData(t *testing.T) {
ss := Setup()
a1 := model.AuthData{}
a1.ClientId = model.NewId()
a1.UserId = model.NewId()
a1.Code = model.NewId()
a1.RedirectUri = "http://example.com"
store.Must(ss.OAuth().SaveAuthData(&a1))
if err := (<-ss.OAuth().GetAuthData(a1.Code)).Err; err != nil {
t.Fatal(err)
}
}
func TestOAuthStoreRemoveAuthData(t *testing.T) {
ss := Setup()
a1 := model.AuthData{}
a1.ClientId = model.NewId()
a1.UserId = model.NewId()
a1.Code = model.NewId()
a1.RedirectUri = "http://example.com"
store.Must(ss.OAuth().SaveAuthData(&a1))
if err := (<-ss.OAuth().RemoveAuthData(a1.Code)).Err; err != nil {
t.Fatal(err)
}
if err := (<-ss.OAuth().GetAuthData(a1.Code)).Err; err == nil {
t.Fatal("should have errored - auth code removed")
}
}
func TestOAuthStoreRemoveAuthDataByUser(t *testing.T) {
ss := Setup()
a1 := model.AuthData{}
a1.ClientId = model.NewId()
a1.UserId = model.NewId()
a1.Code = model.NewId()
a1.RedirectUri = "http://example.com"
store.Must(ss.OAuth().SaveAuthData(&a1))
if err := (<-ss.OAuth().PermanentDeleteAuthDataByUser(a1.UserId)).Err; err != nil {
t.Fatal(err)
}
}
func TestOAuthGetAuthorizedApps(t *testing.T) {
ss := Setup()
a1 := model.OAuthApp{}
a1.CreatorId = model.NewId()
a1.Name = "TestApp" + model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com"
store.Must(ss.OAuth().SaveApp(&a1))
// Lets try and get an Authorized app for a user who hasn't authorized it
if result := <-ss.OAuth().GetAuthorizedApps("fake0123456789abcderfgret1", 0, 1000); result.Err == nil {
if len(result.Data.([]*model.OAuthApp)) > 0 {
t.Fatal("Should have failed. Fake user hasn't authorized the app")
}
} else {
t.Fatal(result.Err)
}
// allow the app
p := model.Preference{}
p.UserId = a1.CreatorId
p.Category = model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP
p.Name = a1.Id
p.Value = "true"
store.Must(ss.Preference().Save(&model.Preferences{p}))
if result := <-ss.OAuth().GetAuthorizedApps(a1.CreatorId, 0, 1000); result.Err != nil {
t.Fatal(result.Err)
} else {
apps := result.Data.([]*model.OAuthApp)
if len(apps) == 0 {
t.Fatal("It should have return apps")
}
}
}
func TestOAuthGetAccessDataByUserForApp(t *testing.T) {
ss := Setup()
a1 := model.OAuthApp{}
a1.CreatorId = model.NewId()
a1.Name = "TestApp" + model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com"
store.Must(ss.OAuth().SaveApp(&a1))
// allow the app
p := model.Preference{}
p.UserId = a1.CreatorId
p.Category = model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP
p.Name = a1.Id
p.Value = "true"
store.Must(ss.Preference().Save(&model.Preferences{p}))
if result := <-ss.OAuth().GetAuthorizedApps(a1.CreatorId, 0, 1000); result.Err != nil {
t.Fatal(result.Err)
} else {
apps := result.Data.([]*model.OAuthApp)
if len(apps) == 0 {
t.Fatal("It should have return apps")
}
}
// save the token
ad1 := model.AccessData{}
ad1.ClientId = a1.Id
ad1.UserId = a1.CreatorId
ad1.Token = model.NewId()
ad1.RefreshToken = model.NewId()
ad1.RedirectUri = "http://example.com"
if err := (<-ss.OAuth().SaveAccessData(&ad1)).Err; err != nil {
t.Fatal(err)
}
if result := <-ss.OAuth().GetAccessDataByUserForApp(a1.CreatorId, a1.Id); result.Err != nil {
t.Fatal(result.Err)
} else {
accessData := result.Data.([]*model.AccessData)
if len(accessData) == 0 {
t.Fatal("It should have return access data")
}
}
}
func TestOAuthStoreDeleteApp(t *testing.T) {
ss := Setup()
a1 := model.OAuthApp{}
a1.CreatorId = model.NewId()
a1.Name = "TestApp" + model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com"
store.Must(ss.OAuth().SaveApp(&a1))
// delete a non-existent app
if err := (<-ss.OAuth().DeleteApp("fakeclientId")).Err; err != nil {
t.Fatal(err)
}
s1 := model.Session{}
s1.UserId = model.NewId()
s1.Token = model.NewId()
s1.IsOAuth = true
store.Must(ss.Session().Save(&s1))
ad1 := model.AccessData{}
ad1.ClientId = a1.Id
ad1.UserId = a1.CreatorId
ad1.Token = s1.Token
ad1.RefreshToken = model.NewId()
ad1.RedirectUri = "http://example.com"
store.Must(ss.OAuth().SaveAccessData(&ad1))
if err := (<-ss.OAuth().DeleteApp(a1.Id)).Err; err != nil {
t.Fatal(err)
}
if err := (<-ss.Session().Get(s1.Token)).Err; err == nil {
t.Fatal("should error - session should be deleted")
}
if err := (<-ss.OAuth().GetAccessData(s1.Token)).Err; err == nil {
t.Fatal("should error - access data should be deleted")
}
func TestOAuthStore(t *testing.T) {
StoreTest(t, storetest.TestOAuthStore)
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@@ -18,10 +18,6 @@ type SqlPreferenceStore struct {
SqlStore
}
const (
FEATURE_TOGGLE_PREFIX = "feature_enabled_"
)
func NewSqlPreferenceStore(sqlStore SqlStore) store.PreferenceStore {
s := &SqlPreferenceStore{sqlStore}
@@ -50,7 +46,7 @@ func (s SqlPreferenceStore) DeleteUnusedFeatures() {
WHERE
Category = :Category
AND Value = :Value
AND Name LIKE '` + FEATURE_TOGGLE_PREFIX + `%'`
AND Name LIKE '` + store.FEATURE_TOGGLE_PREFIX + `%'`
queryParams := map[string]string{
"Category": model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS,
@@ -246,7 +242,7 @@ func (s SqlPreferenceStore) IsFeatureEnabled(feature, userId string) store.Store
WHERE
UserId = :UserId
AND Category = :Category
AND Name = :Name`, map[string]interface{}{"UserId": userId, "Category": model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "Name": FEATURE_TOGGLE_PREFIX + feature}); err != nil {
AND Name = :Name`, map[string]interface{}{"UserId": userId, "Category": model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "Name": store.FEATURE_TOGGLE_PREFIX + feature}); err != nil {
result.Err = model.NewAppError("SqlPreferenceStore.IsFeatureEnabled", "store.sql_preference.is_feature_enabled.app_error", nil, err.Error(), http.StatusInternalServerError)
} else {
result.Data = value == "true"

Просмотреть файл

@@ -6,512 +6,74 @@ package sqlstore
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestPreferenceSave(t *testing.T) {
ss := Setup()
id := model.NewId()
preferences := model.Preferences{
{
UserId: id,
Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW,
Name: model.NewId(),
Value: "value1a",
},
{
UserId: id,
Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW,
Name: model.NewId(),
Value: "value1b",
},
}
if count := store.Must(ss.Preference().Save(&preferences)); count != 2 {
t.Fatal("got incorrect number of rows saved")
}
for _, preference := range preferences {
if data := store.Must(ss.Preference().Get(preference.UserId, preference.Category, preference.Name)).(model.Preference); preference != data {
t.Fatal("got incorrect preference after first Save")
}
}
preferences[0].Value = "value2a"
preferences[1].Value = "value2b"
if count := store.Must(ss.Preference().Save(&preferences)); count != 2 {
t.Fatal("got incorrect number of rows saved")
}
for _, preference := range preferences {
if data := store.Must(ss.Preference().Get(preference.UserId, preference.Category, preference.Name)).(model.Preference); preference != data {
t.Fatal("got incorrect preference after second Save")
}
}
}
func TestPreferenceGet(t *testing.T) {
ss := Setup()
userId := model.NewId()
category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW
name := model.NewId()
preferences := model.Preferences{
{
UserId: userId,
Category: category,
Name: name,
},
{
UserId: userId,
Category: category,
Name: model.NewId(),
},
{
UserId: userId,
Category: model.NewId(),
Name: name,
},
{
UserId: model.NewId(),
Category: category,
Name: name,
},
}
store.Must(ss.Preference().Save(&preferences))
if result := <-ss.Preference().Get(userId, category, name); result.Err != nil {
t.Fatal(result.Err)
} else if data := result.Data.(model.Preference); data != preferences[0] {
t.Fatal("got incorrect preference")
}
// make sure getting a missing preference fails
if result := <-ss.Preference().Get(model.NewId(), model.NewId(), model.NewId()); result.Err == nil {
t.Fatal("no error on getting a missing preference")
}
}
func TestPreferenceGetCategory(t *testing.T) {
ss := Setup()
userId := model.NewId()
category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW
name := model.NewId()
preferences := model.Preferences{
{
UserId: userId,
Category: category,
Name: name,
},
// same user/category, different name
{
UserId: userId,
Category: category,
Name: model.NewId(),
},
// same user/name, different category
{
UserId: userId,
Category: model.NewId(),
Name: name,
},
// same name/category, different user
{
UserId: model.NewId(),
Category: category,
Name: name,
},
}
store.Must(ss.Preference().Save(&preferences))
if result := <-ss.Preference().GetCategory(userId, category); result.Err != nil {
t.Fatal(result.Err)
} else if data := result.Data.(model.Preferences); len(data) != 2 {
t.Fatal("got the wrong number of preferences")
} else if !((data[0] == preferences[0] && data[1] == preferences[1]) || (data[0] == preferences[1] && data[1] == preferences[0])) {
t.Fatal("got incorrect preferences")
}
// make sure getting a missing preference category doesn't fail
if result := <-ss.Preference().GetCategory(model.NewId(), model.NewId()); result.Err != nil {
t.Fatal(result.Err)
} else if data := result.Data.(model.Preferences); len(data) != 0 {
t.Fatal("shouldn't have got any preferences")
}
}
func TestPreferenceGetAll(t *testing.T) {
ss := Setup()
userId := model.NewId()
category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW
name := model.NewId()
preferences := model.Preferences{
{
UserId: userId,
Category: category,
Name: name,
},
// same user/category, different name
{
UserId: userId,
Category: category,
Name: model.NewId(),
},
// same user/name, different category
{
UserId: userId,
Category: model.NewId(),
Name: name,
},
// same name/category, different user
{
UserId: model.NewId(),
Category: category,
Name: name,
},
}
store.Must(ss.Preference().Save(&preferences))
if result := <-ss.Preference().GetAll(userId); result.Err != nil {
t.Fatal(result.Err)
} else if data := result.Data.(model.Preferences); len(data) != 3 {
t.Fatal("got the wrong number of preferences")
} else {
for i := 0; i < 3; i++ {
if data[0] != preferences[i] && data[1] != preferences[i] && data[2] != preferences[i] {
t.Fatal("got incorrect preferences")
}
}
}
}
func TestPreferenceDeleteByUser(t *testing.T) {
ss := Setup()
userId := model.NewId()
category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW
name := model.NewId()
preferences := model.Preferences{
{
UserId: userId,
Category: category,
Name: name,
},
// same user/category, different name
{
UserId: userId,
Category: category,
Name: model.NewId(),
},
// same user/name, different category
{
UserId: userId,
Category: model.NewId(),
Name: name,
},
// same name/category, different user
{
UserId: model.NewId(),
Category: category,
Name: name,
},
}
store.Must(ss.Preference().Save(&preferences))
if result := <-ss.Preference().PermanentDeleteByUser(userId); result.Err != nil {
t.Fatal(result.Err)
}
}
func TestIsFeatureEnabled(t *testing.T) {
ss := Setup()
feature1 := "testFeat1"
feature2 := "testFeat2"
feature3 := "testFeat3"
userId := model.NewId()
category := model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS
features := model.Preferences{
{
UserId: userId,
Category: category,
Name: FEATURE_TOGGLE_PREFIX + feature1,
Value: "true",
},
{
UserId: userId,
Category: category,
Name: model.NewId(),
Value: "false",
},
{
UserId: userId,
Category: model.NewId(),
Name: FEATURE_TOGGLE_PREFIX + feature1,
Value: "false",
},
{
UserId: model.NewId(),
Category: category,
Name: FEATURE_TOGGLE_PREFIX + feature2,
Value: "false",
},
{
UserId: model.NewId(),
Category: category,
Name: FEATURE_TOGGLE_PREFIX + feature3,
Value: "foobar",
},
}
store.Must(ss.Preference().Save(&features))
if result := <-ss.Preference().IsFeatureEnabled(feature1, userId); result.Err != nil {
t.Fatal(result.Err)
} else if data := result.Data.(bool); data != true {
t.Fatalf("got incorrect setting for feature1, %v=%v", true, data)
}
if result := <-ss.Preference().IsFeatureEnabled(feature2, userId); result.Err != nil {
t.Fatal(result.Err)
} else if data := result.Data.(bool); data != false {
t.Fatalf("got incorrect setting for feature2, %v=%v", false, data)
}
// make sure we get false if something different than "true" or "false" has been saved to database
if result := <-ss.Preference().IsFeatureEnabled(feature3, userId); result.Err != nil {
t.Fatal(result.Err)
} else if data := result.Data.(bool); data != false {
t.Fatalf("got incorrect setting for feature3, %v=%v", false, data)
}
// make sure false is returned if a non-existent feature is queried
if result := <-ss.Preference().IsFeatureEnabled("someOtherFeature", userId); result.Err != nil {
t.Fatal(result.Err)
} else if data := result.Data.(bool); data != false {
t.Fatalf("got incorrect setting for non-existent feature 'someOtherFeature', %v=%v", false, data)
}
func TestPreferenceStore(t *testing.T) {
StoreTest(t, storetest.TestPreferenceStore)
}
func TestDeleteUnusedFeatures(t *testing.T) {
ss := Setup()
StoreTest(t, func(t *testing.T, ss store.Store) {
userId1 := model.NewId()
userId2 := model.NewId()
category := model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS
feature1 := "feature1"
feature2 := "feature2"
userId1 := model.NewId()
userId2 := model.NewId()
category := model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS
feature1 := "feature1"
feature2 := "feature2"
features := model.Preferences{
{
UserId: userId1,
Category: category,
Name: store.FEATURE_TOGGLE_PREFIX + feature1,
Value: "true",
},
{
UserId: userId2,
Category: category,
Name: store.FEATURE_TOGGLE_PREFIX + feature1,
Value: "false",
},
{
UserId: userId1,
Category: category,
Name: store.FEATURE_TOGGLE_PREFIX + feature2,
Value: "false",
},
{
UserId: userId2,
Category: category,
Name: store.FEATURE_TOGGLE_PREFIX + feature2,
Value: "true",
},
}
features := model.Preferences{
{
UserId: userId1,
Category: category,
Name: FEATURE_TOGGLE_PREFIX + feature1,
Value: "true",
},
{
UserId: userId2,
Category: category,
Name: FEATURE_TOGGLE_PREFIX + feature1,
Value: "false",
},
{
UserId: userId1,
Category: category,
Name: FEATURE_TOGGLE_PREFIX + feature2,
Value: "false",
},
{
UserId: userId2,
Category: category,
Name: FEATURE_TOGGLE_PREFIX + feature2,
Value: "true",
},
}
store.Must(ss.Preference().Save(&features))
store.Must(ss.Preference().Save(&features))
ss.Preference().(*SqlPreferenceStore).DeleteUnusedFeatures()
ss.Preference().(*SqlPreferenceStore).DeleteUnusedFeatures()
//make sure features with value "false" have actually been deleted from the database
if val, err := ss.Preference().(*SqlPreferenceStore).GetReplica().SelectInt(`SELECT COUNT(*)
FROM Preferences
WHERE Category = :Category
AND Value = :Val
AND Name LIKE '`+FEATURE_TOGGLE_PREFIX+`%'`, map[string]interface{}{"Category": model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "Val": "false"}); err != nil {
t.Fatal(err)
} else if val != 0 {
t.Fatalf("Found %d features with value 'false', expected all to be deleted", val)
}
//
// make sure features with value "true" remain saved
if val, err := ss.Preference().(*SqlPreferenceStore).GetReplica().SelectInt(`SELECT COUNT(*)
FROM Preferences
WHERE Category = :Category
AND Value = :Val
AND Name LIKE '`+FEATURE_TOGGLE_PREFIX+`%'`, map[string]interface{}{"Category": model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "Val": "true"}); err != nil {
t.Fatal(err)
} else if val == 0 {
t.Fatalf("Found %d features with value 'true', expected to find at least %d features", val, 2)
}
}
func TestPreferenceDelete(t *testing.T) {
ss := Setup()
preference := model.Preference{
UserId: model.NewId(),
Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW,
Name: model.NewId(),
Value: "value1a",
}
store.Must(ss.Preference().Save(&model.Preferences{preference}))
if prefs := store.Must(ss.Preference().GetAll(preference.UserId)).(model.Preferences); len([]model.Preference(prefs)) != 1 {
t.Fatal("should've returned 1 preference")
}
if result := <-ss.Preference().Delete(preference.UserId, preference.Category, preference.Name); result.Err != nil {
t.Fatal(result.Err)
}
if prefs := store.Must(ss.Preference().GetAll(preference.UserId)).(model.Preferences); len([]model.Preference(prefs)) != 0 {
t.Fatal("should've returned no preferences")
}
}
func TestPreferenceDeleteCategory(t *testing.T) {
ss := Setup()
category := model.NewId()
userId := model.NewId()
preference1 := model.Preference{
UserId: userId,
Category: category,
Name: model.NewId(),
Value: "value1a",
}
preference2 := model.Preference{
UserId: userId,
Category: category,
Name: model.NewId(),
Value: "value1a",
}
store.Must(ss.Preference().Save(&model.Preferences{preference1, preference2}))
if prefs := store.Must(ss.Preference().GetAll(userId)).(model.Preferences); len([]model.Preference(prefs)) != 2 {
t.Fatal("should've returned 2 preferences")
}
if result := <-ss.Preference().DeleteCategory(userId, category); result.Err != nil {
t.Fatal(result.Err)
}
if prefs := store.Must(ss.Preference().GetAll(userId)).(model.Preferences); len([]model.Preference(prefs)) != 0 {
t.Fatal("should've returned no preferences")
}
}
func TestPreferenceDeleteCategoryAndName(t *testing.T) {
ss := Setup()
category := model.NewId()
name := model.NewId()
userId := model.NewId()
userId2 := model.NewId()
preference1 := model.Preference{
UserId: userId,
Category: category,
Name: name,
Value: "value1a",
}
preference2 := model.Preference{
UserId: userId2,
Category: category,
Name: name,
Value: "value1a",
}
store.Must(ss.Preference().Save(&model.Preferences{preference1, preference2}))
if prefs := store.Must(ss.Preference().GetAll(userId)).(model.Preferences); len([]model.Preference(prefs)) != 1 {
t.Fatal("should've returned 1 preference")
}
if prefs := store.Must(ss.Preference().GetAll(userId2)).(model.Preferences); len([]model.Preference(prefs)) != 1 {
t.Fatal("should've returned 1 preference")
}
if result := <-ss.Preference().DeleteCategoryAndName(category, name); result.Err != nil {
t.Fatal(result.Err)
}
if prefs := store.Must(ss.Preference().GetAll(userId)).(model.Preferences); len([]model.Preference(prefs)) != 0 {
t.Fatal("should've returned no preferences")
}
if prefs := store.Must(ss.Preference().GetAll(userId2)).(model.Preferences); len([]model.Preference(prefs)) != 0 {
t.Fatal("should've returned no preferences")
}
}
func TestPreferenceCleanupFlagsBatch(t *testing.T) {
ss := Setup()
category := model.PREFERENCE_CATEGORY_FLAGGED_POST
userId := model.NewId()
o1 := &model.Post{}
o1.ChannelId = model.NewId()
o1.UserId = userId
o1.Message = "zz" + model.NewId() + "AAAAAAAAAAA"
o1.CreateAt = 1000
o1 = (<-ss.Post().Save(o1)).Data.(*model.Post)
preference1 := model.Preference{
UserId: userId,
Category: category,
Name: o1.Id,
Value: "true",
}
preference2 := model.Preference{
UserId: userId,
Category: category,
Name: model.NewId(),
Value: "true",
}
store.Must(ss.Preference().Save(&model.Preferences{preference1, preference2}))
result := <-ss.Preference().CleanupFlagsBatch(10000)
assert.Nil(t, result.Err)
result = <-ss.Preference().Get(userId, category, preference1.Name)
assert.Nil(t, result.Err)
result = <-ss.Preference().Get(userId, category, preference2.Name)
assert.NotNil(t, result.Err)
//make sure features with value "false" have actually been deleted from the database
if val, err := ss.Preference().(*SqlPreferenceStore).GetReplica().SelectInt(`SELECT COUNT(*)
FROM Preferences
WHERE Category = :Category
AND Value = :Val
AND Name LIKE '`+store.FEATURE_TOGGLE_PREFIX+`%'`, map[string]interface{}{"Category": model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "Val": "false"}); err != nil {
t.Fatal(err)
} else if val != 0 {
t.Fatalf("Found %d features with value 'false', expected all to be deleted", val)
}
//
// make sure features with value "true" remain saved
if val, err := ss.Preference().(*SqlPreferenceStore).GetReplica().SelectInt(`SELECT COUNT(*)
FROM Preferences
WHERE Category = :Category
AND Value = :Val
AND Name LIKE '`+store.FEATURE_TOGGLE_PREFIX+`%'`, map[string]interface{}{"Category": model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "Val": "true"}); err != nil {
t.Fatal(err)
} else if val == 0 {
t.Fatalf("Found %d features with value 'true', expected to find at least %d features", val, 2)
}
})
}

Просмотреть файл

@@ -1,4 +1,4 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package sqlstore
@@ -6,347 +6,9 @@ package sqlstore
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestReactionSave(t *testing.T) {
ss := Setup()
post := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
firstUpdateAt := post.UpdateAt
reaction1 := &model.Reaction{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: model.NewId(),
}
if result := <-ss.Reaction().Save(reaction1); result.Err != nil {
t.Fatal(result.Err)
} else if saved := result.Data.(*model.Reaction); saved.UserId != reaction1.UserId ||
saved.PostId != reaction1.PostId || saved.EmojiName != reaction1.EmojiName {
t.Fatal("should've saved reaction and returned it")
}
var secondUpdateAt int64
if postList := store.Must(ss.Post().Get(reaction1.PostId)).(*model.PostList); !postList.Posts[post.Id].HasReactions {
t.Fatal("should've set HasReactions = true on post")
} else if postList.Posts[post.Id].UpdateAt == firstUpdateAt {
t.Fatal("should've marked post as updated when HasReactions changed")
} else {
secondUpdateAt = postList.Posts[post.Id].UpdateAt
}
if result := <-ss.Reaction().Save(reaction1); result.Err != nil {
t.Log(result.Err)
t.Fatal("should've allowed saving a duplicate reaction")
}
// different user
reaction2 := &model.Reaction{
UserId: model.NewId(),
PostId: reaction1.PostId,
EmojiName: reaction1.EmojiName,
}
if result := <-ss.Reaction().Save(reaction2); result.Err != nil {
t.Fatal(result.Err)
}
if postList := store.Must(ss.Post().Get(reaction2.PostId)).(*model.PostList); postList.Posts[post.Id].UpdateAt != secondUpdateAt {
t.Fatal("shouldn't mark as updated when HasReactions hasn't changed")
}
// different post
reaction3 := &model.Reaction{
UserId: reaction1.UserId,
PostId: model.NewId(),
EmojiName: reaction1.EmojiName,
}
if result := <-ss.Reaction().Save(reaction3); result.Err != nil {
t.Fatal(result.Err)
}
// different emoji
reaction4 := &model.Reaction{
UserId: reaction1.UserId,
PostId: reaction1.PostId,
EmojiName: model.NewId(),
}
if result := <-ss.Reaction().Save(reaction4); result.Err != nil {
t.Fatal(result.Err)
}
// invalid reaction
reaction5 := &model.Reaction{
UserId: reaction1.UserId,
PostId: reaction1.PostId,
}
if result := <-ss.Reaction().Save(reaction5); result.Err == nil {
t.Fatal("should've failed for invalid reaction")
}
}
func TestReactionDelete(t *testing.T) {
ss := Setup()
post := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
reaction := &model.Reaction{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: model.NewId(),
}
store.Must(ss.Reaction().Save(reaction))
firstUpdateAt := store.Must(ss.Post().Get(reaction.PostId)).(*model.PostList).Posts[post.Id].UpdateAt
if result := <-ss.Reaction().Delete(reaction); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.Reaction().GetForPost(post.Id, false); result.Err != nil {
t.Fatal(result.Err)
} else if len(result.Data.([]*model.Reaction)) != 0 {
t.Fatal("should've deleted reaction")
}
if postList := store.Must(ss.Post().Get(post.Id)).(*model.PostList); postList.Posts[post.Id].HasReactions {
t.Fatal("should've set HasReactions = false on post")
} else if postList.Posts[post.Id].UpdateAt == firstUpdateAt {
t.Fatal("shouldn't mark as updated when HasReactions has changed after deleting reactions")
}
}
func TestReactionGetForPost(t *testing.T) {
ss := Setup()
postId := model.NewId()
userId := model.NewId()
reactions := []*model.Reaction{
{
UserId: userId,
PostId: postId,
EmojiName: "smile",
},
{
UserId: model.NewId(),
PostId: postId,
EmojiName: "smile",
},
{
UserId: userId,
PostId: postId,
EmojiName: "sad",
},
{
UserId: userId,
PostId: model.NewId(),
EmojiName: "angry",
},
}
for _, reaction := range reactions {
store.Must(ss.Reaction().Save(reaction))
}
if result := <-ss.Reaction().GetForPost(postId, false); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.([]*model.Reaction); len(returned) != 3 {
t.Fatal("should've returned 3 reactions")
} else {
for _, reaction := range reactions {
found := false
for _, returnedReaction := range returned {
if returnedReaction.UserId == reaction.UserId && returnedReaction.PostId == reaction.PostId &&
returnedReaction.EmojiName == reaction.EmojiName {
found = true
break
}
}
if !found && reaction.PostId == postId {
t.Fatalf("should've returned reaction for post %v", reaction)
} else if found && reaction.PostId != postId {
t.Fatal("shouldn't have returned reaction for another post")
}
}
}
// Should return cached item
if result := <-ss.Reaction().GetForPost(postId, true); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.([]*model.Reaction); len(returned) != 3 {
t.Fatal("should've returned 3 reactions")
} else {
for _, reaction := range reactions {
found := false
for _, returnedReaction := range returned {
if returnedReaction.UserId == reaction.UserId && returnedReaction.PostId == reaction.PostId &&
returnedReaction.EmojiName == reaction.EmojiName {
found = true
break
}
}
if !found && reaction.PostId == postId {
t.Fatalf("should've returned reaction for post %v", reaction)
} else if found && reaction.PostId != postId {
t.Fatal("shouldn't have returned reaction for another post")
}
}
}
}
func TestReactionDeleteAllWithEmojiName(t *testing.T) {
ss := Setup()
emojiToDelete := model.NewId()
post := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
post2 := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
post3 := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
userId := model.NewId()
reactions := []*model.Reaction{
{
UserId: userId,
PostId: post.Id,
EmojiName: emojiToDelete,
},
{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: emojiToDelete,
},
{
UserId: userId,
PostId: post.Id,
EmojiName: "sad",
},
{
UserId: userId,
PostId: post2.Id,
EmojiName: "angry",
},
{
UserId: userId,
PostId: post3.Id,
EmojiName: emojiToDelete,
},
}
for _, reaction := range reactions {
store.Must(ss.Reaction().Save(reaction))
}
if result := <-ss.Reaction().DeleteAllWithEmojiName(emojiToDelete); result.Err != nil {
t.Fatal(result.Err)
}
// check that the reactions were deleted
if returned := store.Must(ss.Reaction().GetForPost(post.Id, false)).([]*model.Reaction); len(returned) != 1 {
t.Fatal("should've only removed reactions with emoji name")
} else {
for _, reaction := range returned {
if reaction.EmojiName == "smile" {
t.Fatal("should've removed reaction with emoji name")
}
}
}
if returned := store.Must(ss.Reaction().GetForPost(post2.Id, false)).([]*model.Reaction); len(returned) != 1 {
t.Fatal("should've only removed reactions with emoji name")
}
if returned := store.Must(ss.Reaction().GetForPost(post3.Id, false)).([]*model.Reaction); len(returned) != 0 {
t.Fatal("should've only removed reactions with emoji name")
}
// check that the posts are updated
if postList := store.Must(ss.Post().Get(post.Id)).(*model.PostList); !postList.Posts[post.Id].HasReactions {
t.Fatal("post should still have reactions")
}
if postList := store.Must(ss.Post().Get(post2.Id)).(*model.PostList); !postList.Posts[post2.Id].HasReactions {
t.Fatal("post should still have reactions")
}
if postList := store.Must(ss.Post().Get(post3.Id)).(*model.PostList); postList.Posts[post3.Id].HasReactions {
t.Fatal("post shouldn't have reactions any more")
}
}
func TestReactionStorePermanentDeleteBatch(t *testing.T) {
ss := Setup()
post := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
reactions := []*model.Reaction{
{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: "sad",
CreateAt: 1000,
},
{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: "sad",
CreateAt: 1500,
},
{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: "sad",
CreateAt: 2000,
},
{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: "sad",
CreateAt: 2000,
},
}
// Need to hang on to a reaction to delete later in order to clear the cache, as "allowFromCache" isn't honoured any more.
var lastReaction *model.Reaction
for _, reaction := range reactions {
lastReaction = store.Must(ss.Reaction().Save(reaction)).(*model.Reaction)
}
if returned := store.Must(ss.Reaction().GetForPost(post.Id, false)).([]*model.Reaction); len(returned) != 4 {
t.Fatal("expected 4 reactions")
}
store.Must(ss.Reaction().PermanentDeleteBatch(1800, 1000))
// This is to force a clear of the cache.
store.Must(ss.Reaction().Delete(lastReaction))
if returned := store.Must(ss.Reaction().GetForPost(post.Id, false)).([]*model.Reaction); len(returned) != 1 {
t.Fatalf("expected 1 reaction. Got: %v", len(returned))
}
func TestReactionStore(t *testing.T) {
StoreTest(t, storetest.TestReactionStore)
}

Просмотреть файл

@@ -6,253 +6,9 @@ package sqlstore
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestSessionStoreSave(t *testing.T) {
ss := Setup()
s1 := model.Session{}
s1.UserId = model.NewId()
if err := (<-ss.Session().Save(&s1)).Err; err != nil {
t.Fatal(err)
}
}
func TestSessionGet(t *testing.T) {
ss := Setup()
s1 := model.Session{}
s1.UserId = model.NewId()
store.Must(ss.Session().Save(&s1))
s2 := model.Session{}
s2.UserId = s1.UserId
store.Must(ss.Session().Save(&s2))
s3 := model.Session{}
s3.UserId = s1.UserId
s3.ExpiresAt = 1
store.Must(ss.Session().Save(&s3))
if rs1 := (<-ss.Session().Get(s1.Id)); rs1.Err != nil {
t.Fatal(rs1.Err)
} else {
if rs1.Data.(*model.Session).Id != s1.Id {
t.Fatal("should match")
}
}
if rs2 := (<-ss.Session().GetSessions(s1.UserId)); rs2.Err != nil {
t.Fatal(rs2.Err)
} else {
if len(rs2.Data.([]*model.Session)) != 2 {
t.Fatal("should match len")
}
}
}
func TestSessionGetWithDeviceId(t *testing.T) {
ss := Setup()
s1 := model.Session{}
s1.UserId = model.NewId()
s1.ExpiresAt = model.GetMillis() + 10000
store.Must(ss.Session().Save(&s1))
s2 := model.Session{}
s2.UserId = s1.UserId
s2.DeviceId = model.NewId()
s2.ExpiresAt = model.GetMillis() + 10000
store.Must(ss.Session().Save(&s2))
s3 := model.Session{}
s3.UserId = s1.UserId
s3.ExpiresAt = 1
s3.DeviceId = model.NewId()
store.Must(ss.Session().Save(&s3))
if rs1 := (<-ss.Session().GetSessionsWithActiveDeviceIds(s1.UserId)); rs1.Err != nil {
t.Fatal(rs1.Err)
} else {
if len(rs1.Data.([]*model.Session)) != 1 {
t.Fatal("should match len")
}
}
}
func TestSessionRemove(t *testing.T) {
ss := Setup()
s1 := model.Session{}
s1.UserId = model.NewId()
store.Must(ss.Session().Save(&s1))
if rs1 := (<-ss.Session().Get(s1.Id)); rs1.Err != nil {
t.Fatal(rs1.Err)
} else {
if rs1.Data.(*model.Session).Id != s1.Id {
t.Fatal("should match")
}
}
store.Must(ss.Session().Remove(s1.Id))
if rs2 := (<-ss.Session().Get(s1.Id)); rs2.Err == nil {
t.Fatal("should have been removed")
}
}
func TestSessionRemoveAll(t *testing.T) {
ss := Setup()
s1 := model.Session{}
s1.UserId = model.NewId()
store.Must(ss.Session().Save(&s1))
if rs1 := (<-ss.Session().Get(s1.Id)); rs1.Err != nil {
t.Fatal(rs1.Err)
} else {
if rs1.Data.(*model.Session).Id != s1.Id {
t.Fatal("should match")
}
}
store.Must(ss.Session().RemoveAllSessions())
if rs2 := (<-ss.Session().Get(s1.Id)); rs2.Err == nil {
t.Fatal("should have been removed")
}
}
func TestSessionRemoveByUser(t *testing.T) {
ss := Setup()
s1 := model.Session{}
s1.UserId = model.NewId()
store.Must(ss.Session().Save(&s1))
if rs1 := (<-ss.Session().Get(s1.Id)); rs1.Err != nil {
t.Fatal(rs1.Err)
} else {
if rs1.Data.(*model.Session).Id != s1.Id {
t.Fatal("should match")
}
}
store.Must(ss.Session().PermanentDeleteSessionsByUser(s1.UserId))
if rs2 := (<-ss.Session().Get(s1.Id)); rs2.Err == nil {
t.Fatal("should have been removed")
}
}
func TestSessionRemoveToken(t *testing.T) {
ss := Setup()
s1 := model.Session{}
s1.UserId = model.NewId()
store.Must(ss.Session().Save(&s1))
if rs1 := (<-ss.Session().Get(s1.Id)); rs1.Err != nil {
t.Fatal(rs1.Err)
} else {
if rs1.Data.(*model.Session).Id != s1.Id {
t.Fatal("should match")
}
}
store.Must(ss.Session().Remove(s1.Token))
if rs2 := (<-ss.Session().Get(s1.Id)); rs2.Err == nil {
t.Fatal("should have been removed")
}
if rs3 := (<-ss.Session().GetSessions(s1.UserId)); rs3.Err != nil {
t.Fatal(rs3.Err)
} else {
if len(rs3.Data.([]*model.Session)) != 0 {
t.Fatal("should match len")
}
}
}
func TestSessionUpdateDeviceId(t *testing.T) {
ss := Setup()
s1 := model.Session{}
s1.UserId = model.NewId()
store.Must(ss.Session().Save(&s1))
if rs1 := (<-ss.Session().UpdateDeviceId(s1.Id, model.PUSH_NOTIFY_APPLE+":1234567890", s1.ExpiresAt)); rs1.Err != nil {
t.Fatal(rs1.Err)
}
s2 := model.Session{}
s2.UserId = model.NewId()
store.Must(ss.Session().Save(&s2))
if rs2 := (<-ss.Session().UpdateDeviceId(s2.Id, model.PUSH_NOTIFY_APPLE+":1234567890", s1.ExpiresAt)); rs2.Err != nil {
t.Fatal(rs2.Err)
}
}
func TestSessionUpdateDeviceId2(t *testing.T) {
ss := Setup()
s1 := model.Session{}
s1.UserId = model.NewId()
store.Must(ss.Session().Save(&s1))
if rs1 := (<-ss.Session().UpdateDeviceId(s1.Id, model.PUSH_NOTIFY_APPLE_REACT_NATIVE+":1234567890", s1.ExpiresAt)); rs1.Err != nil {
t.Fatal(rs1.Err)
}
s2 := model.Session{}
s2.UserId = model.NewId()
store.Must(ss.Session().Save(&s2))
if rs2 := (<-ss.Session().UpdateDeviceId(s2.Id, model.PUSH_NOTIFY_APPLE_REACT_NATIVE+":1234567890", s1.ExpiresAt)); rs2.Err != nil {
t.Fatal(rs2.Err)
}
}
func TestSessionStoreUpdateLastActivityAt(t *testing.T) {
ss := Setup()
s1 := model.Session{}
s1.UserId = model.NewId()
store.Must(ss.Session().Save(&s1))
if err := (<-ss.Session().UpdateLastActivityAt(s1.Id, 1234567890)).Err; err != nil {
t.Fatal(err)
}
if r1 := <-ss.Session().Get(s1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.Session).LastActivityAt != 1234567890 {
t.Fatal("LastActivityAt not updated correctly")
}
}
}
func TestSessionCount(t *testing.T) {
ss := Setup()
s1 := model.Session{}
s1.UserId = model.NewId()
s1.ExpiresAt = model.GetMillis() + 100000
store.Must(ss.Session().Save(&s1))
if r1 := <-ss.Session().AnalyticsSessionCount(); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(int64) == 0 {
t.Fatal("should have at least 1 session")
}
}
func TestSessionStore(t *testing.T) {
StoreTest(t, storetest.TestSessionStore)
}

Просмотреть файл

@@ -1,4 +1,4 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package sqlstore
@@ -6,100 +6,9 @@ package sqlstore
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestSqlStatusStore(t *testing.T) {
ss := Setup()
status := &model.Status{UserId: model.NewId(), Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""}
if err := (<-ss.Status().SaveOrUpdate(status)).Err; err != nil {
t.Fatal(err)
}
status.LastActivityAt = 10
if err := (<-ss.Status().SaveOrUpdate(status)).Err; err != nil {
t.Fatal(err)
}
if err := (<-ss.Status().Get(status.UserId)).Err; err != nil {
t.Fatal(err)
}
status2 := &model.Status{UserId: model.NewId(), Status: model.STATUS_AWAY, Manual: false, LastActivityAt: 0, ActiveChannel: ""}
if err := (<-ss.Status().SaveOrUpdate(status2)).Err; err != nil {
t.Fatal(err)
}
status3 := &model.Status{UserId: model.NewId(), Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""}
if err := (<-ss.Status().SaveOrUpdate(status3)).Err; err != nil {
t.Fatal(err)
}
if result := <-ss.Status().GetOnlineAway(); result.Err != nil {
t.Fatal(result.Err)
} else {
statuses := result.Data.([]*model.Status)
for _, status := range statuses {
if status.Status == model.STATUS_OFFLINE {
t.Fatal("should not have returned offline statuses")
}
}
}
if result := <-ss.Status().GetOnline(); result.Err != nil {
t.Fatal(result.Err)
} else {
statuses := result.Data.([]*model.Status)
for _, status := range statuses {
if status.Status != model.STATUS_ONLINE {
t.Fatal("should not have returned offline statuses")
}
}
}
if result := <-ss.Status().GetByIds([]string{status.UserId, "junk"}); result.Err != nil {
t.Fatal(result.Err)
} else {
statuses := result.Data.([]*model.Status)
if len(statuses) != 1 {
t.Fatal("should only have 1 status")
}
}
if err := (<-ss.Status().ResetAll()).Err; err != nil {
t.Fatal(err)
}
if result := <-ss.Status().Get(status.UserId); result.Err != nil {
t.Fatal(result.Err)
} else {
status := result.Data.(*model.Status)
if status.Status != model.STATUS_OFFLINE {
t.Fatal("should be offline")
}
}
if result := <-ss.Status().UpdateLastActivityAt(status.UserId, 10); result.Err != nil {
t.Fatal(result.Err)
}
}
func TestActiveUserCount(t *testing.T) {
ss := Setup()
status := &model.Status{UserId: model.NewId(), Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""}
store.Must(ss.Status().SaveOrUpdate(status))
if result := <-ss.Status().GetTotalActiveUsersCount(); result.Err != nil {
t.Fatal(result.Err)
} else {
count := result.Data.(int64)
if count <= 0 {
t.Fatal()
}
}
func TestStatusStore(t *testing.T) {
StoreTest(t, storetest.TestStatusStore)
}

Просмотреть файл

@@ -4,13 +4,15 @@
package sqlstore
import (
"testing"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/utils"
)
var sqlStore store.Store
func Setup() store.Store {
func StoreTest(t *testing.T, f func(*testing.T, store.Store)) {
if sqlStore == nil {
utils.TranslationsPreInit()
utils.LoadConfig("config.json")
@@ -19,133 +21,5 @@ func Setup() store.Store {
sqlStore.MarkSystemRanUnitTests()
}
return sqlStore
f(t, sqlStore)
}
/*
func TestSqlStore1(t *testing.T) {
utils.TranslationsPreInit()
utils.LoadConfig("config.json")
utils.Cfg.SqlSettings.Trace = true
store := NewSqlStore()
ss.Close()
utils.Cfg.SqlSettings.DataSourceReplicas = []string{utils.Cfg.SqlSettings.DataSource}
store = NewSqlStore()
ss.TotalMasterDbConnections()
ss.TotalReadDbConnections()
ss.Close()
utils.LoadConfig("config.json")
}
func TestAlertDbCmds(t *testing.T) {
ss := Setup()
sqlStore := store.(SqlStore)
if !sqlStore.DoesTableExist("Systems") {
t.Fatal("Failed table exists")
}
if sqlStore.DoesColumnExist("Systems", "Test") {
t.Fatal("Column should not exist")
}
if !sqlStore.CreateColumnIfNotExists("Systems", "Test", "VARCHAR(50)", "VARCHAR(50)", "") {
t.Fatal("Failed to create column")
}
maxLen := sqlStore.GetMaxLengthOfColumnIfExists("Systems", "Test")
if maxLen != "50" {
t.Fatal("Failed to get max length found " + maxLen)
}
if !sqlStore.AlterColumnTypeIfExists("Systems", "Test", "VARCHAR(25)", "VARCHAR(25)") {
t.Fatal("failed to alter column size")
}
maxLen2 := sqlStore.GetMaxLengthOfColumnIfExists("Systems", "Test")
if maxLen2 != "25" {
t.Fatal("Failed to get max length")
}
if !sqlStore.RenameColumnIfExists("Systems", "Test", "Test1", "VARCHAR(25)") {
t.Fatal("Failed to rename column")
}
if sqlStore.DoesColumnExist("Systems", "Test") {
t.Fatal("Column should not exist")
}
if !sqlStore.DoesColumnExist("Systems", "Test1") {
t.Fatal("Column should exist")
}
sqlStore.CreateIndexIfNotExists("idx_systems_test1", "Systems", "Test1")
sqlStore.RemoveIndexIfExists("idx_systems_test1", "Systems")
sqlStore.CreateFullTextIndexIfNotExists("idx_systems_test1", "Systems", "Test1")
sqlStore.RemoveIndexIfExists("idx_systems_test1", "Systems")
if !sqlStore.RemoveColumnIfExists("Systems", "Test1") {
t.Fatal("Failed to remove columns")
}
if sqlStore.DoesColumnExist("Systems", "Test1") {
t.Fatal("Column should not exist")
}
}
func TestCreateIndexIfNotExists(t *testing.T) {
ss := Setup()
sqlStore := store.(SqlStore)
defer sqlStore.RemoveColumnIfExists("Systems", "Test")
if !sqlStore.CreateColumnIfNotExists("Systems", "Test", "VARCHAR(50)", "VARCHAR(50)", "") {
t.Fatal("Failed to create test column")
}
defer sqlStore.RemoveIndexIfExists("idx_systems_create_index_test", "Systems")
if !sqlStore.CreateIndexIfNotExists("idx_systems_create_index_test", "Systems", "Test") {
t.Fatal("Should've created test index")
}
if sqlStore.CreateIndexIfNotExists("idx_systems_create_index_test", "Systems", "Test") {
t.Fatal("Shouldn't have created index that already exists")
}
}
func TestRemoveIndexIfExists(t *testing.T) {
ss := Setup()
sqlStore := store.(SqlStore)
defer sqlStore.RemoveColumnIfExists("Systems", "Test")
if !sqlStore.CreateColumnIfNotExists("Systems", "Test", "VARCHAR(50)", "VARCHAR(50)", "") {
t.Fatal("Failed to create test column")
}
if sqlStore.RemoveIndexIfExists("idx_systems_remove_index_test", "Systems") {
t.Fatal("Should've failed to remove index that doesn't exist")
}
defer sqlStore.RemoveIndexIfExists("idx_systems_remove_index_test", "Systems")
if !sqlStore.CreateIndexIfNotExists("idx_systems_remove_index_test", "Systems", "Test") {
t.Fatal("Should've created test index")
}
if !sqlStore.RemoveIndexIfExists("idx_systems_remove_index_test", "Systems") {
t.Fatal("Should've removed index that exists")
}
if sqlStore.RemoveIndexIfExists("idx_systems_remove_index_test", "Systems") {
t.Fatal("Should've failed to remove index that was already removed")
}
}
*/

Просмотреть файл

@@ -6,52 +6,9 @@ package sqlstore
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestSqlSystemStore(t *testing.T) {
ss := Setup()
system := &model.System{Name: model.NewId(), Value: "value"}
store.Must(ss.System().Save(system))
result := <-ss.System().Get()
systems := result.Data.(model.StringMap)
if systems[system.Name] != system.Value {
t.Fatal()
}
system.Value = "value2"
store.Must(ss.System().Update(system))
result2 := <-ss.System().Get()
systems2 := result2.Data.(model.StringMap)
if systems2[system.Name] != system.Value {
t.Fatal()
}
result3 := <-ss.System().GetByName(system.Name)
rsystem := result3.Data.(*model.System)
if rsystem.Value != system.Value {
t.Fatal()
}
}
func TestSqlSystemStoreSaveOrUpdate(t *testing.T) {
ss := Setup()
system := &model.System{Name: model.NewId(), Value: "value"}
if err := (<-ss.System().SaveOrUpdate(system)).Err; err != nil {
t.Fatal(err)
}
system.Value = "value2"
if r := <-ss.System().SaveOrUpdate(system); r.Err != nil {
t.Fatal(r.Err)
}
func TestSystemStore(t *testing.T) {
StoreTest(t, storetest.TestSystemStore)
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@@ -11,31 +11,31 @@ import (
)
func TestStoreUpgrade(t *testing.T) {
ss := Setup()
StoreTest(t, func(t *testing.T, ss store.Store) {
saveSchemaVersion(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore), VERSION_3_0_0)
UpgradeDatabase(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore))
saveSchemaVersion(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore), VERSION_3_0_0)
UpgradeDatabase(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore))
saveSchemaVersion(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore), "")
UpgradeDatabase(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore))
saveSchemaVersion(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore), "")
UpgradeDatabase(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore))
})
}
func TestSaveSchemaVersion(t *testing.T) {
ss := Setup()
StoreTest(t, func(t *testing.T, ss store.Store) {
saveSchemaVersion(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore), VERSION_3_0_0)
if result := <-ss.System().Get(); result.Err != nil {
t.Fatal(result.Err)
} else {
props := result.Data.(model.StringMap)
if props["Version"] != VERSION_3_0_0 {
t.Fatal("version not updated")
}
}
saveSchemaVersion(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore), VERSION_3_0_0)
if result := <-ss.System().Get(); result.Err != nil {
t.Fatal(result.Err)
} else {
props := result.Data.(model.StringMap)
if props["Version"] != VERSION_3_0_0 {
if ss.(*store.LayeredStore).DatabaseLayer.(SqlStore).GetCurrentSchemaVersion() != VERSION_3_0_0 {
t.Fatal("version not updated")
}
}
if ss.(*store.LayeredStore).DatabaseLayer.(SqlStore).GetCurrentSchemaVersion() != VERSION_3_0_0 {
t.Fatal("version not updated")
}
saveSchemaVersion(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore), model.CurrentVersion)
saveSchemaVersion(ss.(*store.LayeredStore).DatabaseLayer.(SqlStore), model.CurrentVersion)
})
}

Просмотреть файл

@@ -1,4 +1,4 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package sqlstore
@@ -6,82 +6,9 @@ package sqlstore
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestUserAccessTokenSaveGetDelete(t *testing.T) {
ss := Setup()
uat := &model.UserAccessToken{
Token: model.NewId(),
UserId: model.NewId(),
Description: "testtoken",
}
s1 := model.Session{}
s1.UserId = uat.UserId
s1.Token = uat.Token
store.Must(ss.Session().Save(&s1))
if result := <-ss.UserAccessToken().Save(uat); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.UserAccessToken().Get(uat.Id); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.(*model.UserAccessToken); received.Token != uat.Token {
t.Fatal("received incorrect token after save")
}
if result := <-ss.UserAccessToken().GetByToken(uat.Token); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.(*model.UserAccessToken); received.Token != uat.Token {
t.Fatal("received incorrect token after save")
}
if result := <-ss.UserAccessToken().GetByToken("notarealtoken"); result.Err == nil {
t.Fatal("should have failed on bad token")
}
if result := <-ss.UserAccessToken().GetByUser(uat.UserId, 0, 100); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.([]*model.UserAccessToken); len(received) != 1 {
t.Fatal("received incorrect number of tokens after save")
}
if result := <-ss.UserAccessToken().Delete(uat.Id); result.Err != nil {
t.Fatal(result.Err)
}
if err := (<-ss.Session().Get(s1.Token)).Err; err == nil {
t.Fatal("should error - session should be deleted")
}
if err := (<-ss.UserAccessToken().GetByToken(s1.Token)).Err; err == nil {
t.Fatal("should error - access token should be deleted")
}
s2 := model.Session{}
s2.UserId = uat.UserId
s2.Token = uat.Token
store.Must(ss.Session().Save(&s2))
if result := <-ss.UserAccessToken().Save(uat); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.UserAccessToken().DeleteAllForUser(uat.UserId); result.Err != nil {
t.Fatal(result.Err)
}
if err := (<-ss.Session().Get(s2.Token)).Err; err == nil {
t.Fatal("should error - session should be deleted")
}
if err := (<-ss.UserAccessToken().GetByToken(s2.Token)).Err; err == nil {
t.Fatal("should error - access token should be deleted")
}
func TestUserAccessTokenStore(t *testing.T) {
StoreTest(t, storetest.TestUserAccessTokenStore)
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@@ -5,512 +5,10 @@ package sqlstore
import (
"testing"
"time"
"net/http"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store/storetest"
)
func TestWebhookStoreSaveIncoming(t *testing.T) {
ss := Setup()
o1 := buildIncomingWebhook()
if err := (<-ss.Webhook().SaveIncoming(o1)).Err; err != nil {
t.Fatal("couldn't save item", err)
}
if err := (<-ss.Webhook().SaveIncoming(o1)).Err; err == nil {
t.Fatal("shouldn't be able to update from save")
}
}
func TestWebhookStoreUpdateIncoming(t *testing.T) {
ss := Setup()
o1 := buildIncomingWebhook()
o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
previousUpdatedAt := o1.UpdateAt
o1.DisplayName = "TestHook"
time.Sleep(10 * time.Millisecond)
if result := (<-ss.Webhook().UpdateIncoming(o1)); result.Err != nil {
t.Fatal("updation of incoming hook failed", result.Err)
} else {
if result.Data.(*model.IncomingWebhook).UpdateAt == previousUpdatedAt {
t.Fatal("should have updated the UpdatedAt of the hook")
}
if result.Data.(*model.IncomingWebhook).DisplayName != "TestHook" {
t.Fatal("display name is not updated")
}
}
}
func TestWebhookStoreGetIncoming(t *testing.T) {
ss := Setup()
o1 := buildIncomingWebhook()
o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-ss.Webhook().GetIncoming(o1.Id, false); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if r1 := <-ss.Webhook().GetIncoming(o1.Id, true); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if err := (<-ss.Webhook().GetIncoming("123", false)).Err; err == nil {
t.Fatal("Missing id should have failed")
}
if err := (<-ss.Webhook().GetIncoming("123", true)).Err; err == nil {
t.Fatal("Missing id should have failed")
}
if err := (<-ss.Webhook().GetIncoming("123", true)).Err; err.StatusCode != http.StatusNotFound {
t.Fatal("Should have set the status as not found for missing id")
}
}
func TestWebhookStoreGetIncomingList(t *testing.T) {
ss := Setup()
o1 := &model.IncomingWebhook{}
o1.ChannelId = model.NewId()
o1.UserId = model.NewId()
o1.TeamId = model.NewId()
o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-ss.Webhook().GetIncomingList(0, 1000); r1.Err != nil {
t.Fatal(r1.Err)
} else {
found := false
hooks := r1.Data.([]*model.IncomingWebhook)
for _, hook := range hooks {
if hook.Id == o1.Id {
found = true
}
}
if !found {
t.Fatal("missing webhook")
}
}
if result := <-ss.Webhook().GetIncomingList(0, 1); result.Err != nil {
t.Fatal(result.Err)
} else {
if len(result.Data.([]*model.IncomingWebhook)) != 1 {
t.Fatal("only 1 should be returned")
}
}
}
func TestWebhookStoreGetIncomingByTeam(t *testing.T) {
ss := Setup()
o1 := buildIncomingWebhook()
o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-ss.Webhook().GetIncomingByTeam(o1.TeamId, 0, 100); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.([]*model.IncomingWebhook)[0].CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if result := <-ss.Webhook().GetIncomingByTeam("123", 0, 100); result.Err != nil {
t.Fatal(result.Err)
} else {
if len(result.Data.([]*model.IncomingWebhook)) != 0 {
t.Fatal("no webhooks should have returned")
}
}
}
func TestWebhookStoreDeleteIncoming(t *testing.T) {
ss := Setup()
o1 := buildIncomingWebhook()
o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-ss.Webhook().GetIncoming(o1.Id, true); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if r2 := <-ss.Webhook().DeleteIncoming(o1.Id, model.GetMillis()); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Webhook().GetIncoming(o1.Id, true)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func TestWebhookStoreDeleteIncomingByChannel(t *testing.T) {
ss := Setup()
o1 := buildIncomingWebhook()
o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-ss.Webhook().GetIncoming(o1.Id, true); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if r2 := <-ss.Webhook().PermanentDeleteIncomingByChannel(o1.ChannelId); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Webhook().GetIncoming(o1.Id, true)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func TestWebhookStoreDeleteIncomingByUser(t *testing.T) {
ss := Setup()
o1 := buildIncomingWebhook()
o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-ss.Webhook().GetIncoming(o1.Id, true); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if r2 := <-ss.Webhook().PermanentDeleteIncomingByUser(o1.UserId); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Webhook().GetIncoming(o1.Id, true)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func buildIncomingWebhook() *model.IncomingWebhook {
o1 := &model.IncomingWebhook{}
o1.ChannelId = model.NewId()
o1.UserId = model.NewId()
o1.TeamId = model.NewId()
return o1
}
func TestWebhookStoreSaveOutgoing(t *testing.T) {
ss := Setup()
o1 := model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
if err := (<-ss.Webhook().SaveOutgoing(&o1)).Err; err != nil {
t.Fatal("couldn't save item", err)
}
if err := (<-ss.Webhook().SaveOutgoing(&o1)).Err; err == nil {
t.Fatal("shouldn't be able to update from save")
}
}
func TestWebhookStoreGetOutgoing(t *testing.T) {
ss := Setup()
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-ss.Webhook().GetOutgoing(o1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.OutgoingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if err := (<-ss.Webhook().GetOutgoing("123")).Err; err == nil {
t.Fatal("Missing id should have failed")
}
}
func TestWebhookStoreGetOutgoingList(t *testing.T) {
ss := Setup()
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
o2 := &model.OutgoingWebhook{}
o2.ChannelId = model.NewId()
o2.CreatorId = model.NewId()
o2.TeamId = model.NewId()
o2.CallbackURLs = []string{"http://nowhere.com/"}
o2 = (<-ss.Webhook().SaveOutgoing(o2)).Data.(*model.OutgoingWebhook)
if r1 := <-ss.Webhook().GetOutgoingList(0, 1000); r1.Err != nil {
t.Fatal(r1.Err)
} else {
hooks := r1.Data.([]*model.OutgoingWebhook)
found1 := false
found2 := false
for _, hook := range hooks {
if hook.CreateAt != o1.CreateAt {
found1 = true
}
if hook.CreateAt != o2.CreateAt {
found2 = true
}
}
if !found1 {
t.Fatal("missing hook1")
}
if !found2 {
t.Fatal("missing hook2")
}
}
if result := <-ss.Webhook().GetOutgoingList(0, 2); result.Err != nil {
t.Fatal(result.Err)
} else {
if len(result.Data.([]*model.OutgoingWebhook)) != 2 {
t.Fatal("wrong number of hooks returned")
}
}
}
func TestWebhookStoreGetOutgoingByChannel(t *testing.T) {
ss := Setup()
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-ss.Webhook().GetOutgoingByChannel(o1.ChannelId, 0, 100); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.([]*model.OutgoingWebhook)[0].CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if result := <-ss.Webhook().GetOutgoingByChannel("123", -1, -1); result.Err != nil {
t.Fatal(result.Err)
} else {
if len(result.Data.([]*model.OutgoingWebhook)) != 0 {
t.Fatal("no webhooks should have returned")
}
}
}
func TestWebhookStoreGetOutgoingByTeam(t *testing.T) {
ss := Setup()
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-ss.Webhook().GetOutgoingByTeam(o1.TeamId, 0, 100); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.([]*model.OutgoingWebhook)[0].CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if result := <-ss.Webhook().GetOutgoingByTeam("123", -1, -1); result.Err != nil {
t.Fatal(result.Err)
} else {
if len(result.Data.([]*model.OutgoingWebhook)) != 0 {
t.Fatal("no webhooks should have returned")
}
}
}
func TestWebhookStoreDeleteOutgoing(t *testing.T) {
ss := Setup()
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-ss.Webhook().GetOutgoing(o1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.OutgoingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if r2 := <-ss.Webhook().DeleteOutgoing(o1.Id, model.GetMillis()); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Webhook().GetOutgoing(o1.Id)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func TestWebhookStoreDeleteOutgoingByChannel(t *testing.T) {
ss := Setup()
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-ss.Webhook().GetOutgoing(o1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.OutgoingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if r2 := <-ss.Webhook().PermanentDeleteOutgoingByChannel(o1.ChannelId); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Webhook().GetOutgoing(o1.Id)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func TestWebhookStoreDeleteOutgoingByUser(t *testing.T) {
ss := Setup()
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-ss.Webhook().GetOutgoing(o1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.OutgoingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if r2 := <-ss.Webhook().PermanentDeleteOutgoingByUser(o1.CreatorId); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Webhook().GetOutgoing(o1.Id)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func TestWebhookStoreUpdateOutgoing(t *testing.T) {
ss := Setup()
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
o1.Token = model.NewId()
if r2 := <-ss.Webhook().UpdateOutgoing(o1); r2.Err != nil {
t.Fatal(r2.Err)
}
}
func TestWebhookStoreCountIncoming(t *testing.T) {
ss := Setup()
o1 := &model.IncomingWebhook{}
o1.ChannelId = model.NewId()
o1.UserId = model.NewId()
o1.TeamId = model.NewId()
o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r := <-ss.Webhook().AnalyticsIncomingCount(""); r.Err != nil {
t.Fatal(r.Err)
} else {
if r.Data.(int64) == 0 {
t.Fatal("should have at least 1 incoming hook")
}
}
}
func TestWebhookStoreCountOutgoing(t *testing.T) {
ss := Setup()
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r := <-ss.Webhook().AnalyticsOutgoingCount(""); r.Err != nil {
t.Fatal(r.Err)
} else {
if r.Data.(int64) == 0 {
t.Fatal("should have at least 1 outgoing hook")
}
}
func TestWebhookStore(t *testing.T) {
StoreTest(t, storetest.TestWebhookStore)
}

91
store/storetest/audit_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,91 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"time"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestAuditStore(t *testing.T, ss store.Store) {
t.Run("", func(t *testing.T) { testAuditStore(t, ss) })
t.Run("PermanentDeleteBatch", func(t *testing.T) { testAuditStorePermanentDeleteBatch(t, ss) })
}
func testAuditStore(t *testing.T, ss store.Store) {
audit := &model.Audit{UserId: model.NewId(), IpAddress: "ipaddress", Action: "Action"}
store.Must(ss.Audit().Save(audit))
time.Sleep(100 * time.Millisecond)
store.Must(ss.Audit().Save(audit))
time.Sleep(100 * time.Millisecond)
store.Must(ss.Audit().Save(audit))
time.Sleep(100 * time.Millisecond)
audit.ExtraInfo = "extra"
time.Sleep(100 * time.Millisecond)
store.Must(ss.Audit().Save(audit))
time.Sleep(100 * time.Millisecond)
c := ss.Audit().Get(audit.UserId, 0, 100)
result := <-c
audits := result.Data.(model.Audits)
if len(audits) != 4 {
t.Fatal("Failed to save and retrieve 4 audit logs")
}
if audits[0].ExtraInfo != "extra" {
t.Fatal("Failed to save property for extra info")
}
c = ss.Audit().Get("missing", 0, 100)
result = <-c
audits = result.Data.(model.Audits)
if len(audits) != 0 {
t.Fatal("Should have returned empty because user_id is missing")
}
c = ss.Audit().Get("", 0, 100)
result = <-c
audits = result.Data.(model.Audits)
if len(audits) < 4 {
t.Fatal("Failed to save and retrieve 4 audit logs")
}
if r2 := <-ss.Audit().PermanentDeleteByUser(audit.UserId); r2.Err != nil {
t.Fatal(r2.Err)
}
}
func testAuditStorePermanentDeleteBatch(t *testing.T, ss store.Store) {
a1 := &model.Audit{UserId: model.NewId(), IpAddress: "ipaddress", Action: "Action"}
store.Must(ss.Audit().Save(a1))
time.Sleep(10 * time.Millisecond)
a2 := &model.Audit{UserId: a1.UserId, IpAddress: "ipaddress", Action: "Action"}
store.Must(ss.Audit().Save(a2))
time.Sleep(10 * time.Millisecond)
cutoff := model.GetMillis()
time.Sleep(10 * time.Millisecond)
a3 := &model.Audit{UserId: a1.UserId, IpAddress: "ipaddress", Action: "Action"}
store.Must(ss.Audit().Save(a3))
if r := <-ss.Audit().Get(a1.UserId, 0, 100); len(r.Data.(model.Audits)) != 3 {
t.Fatal("Expected 3 audits. Got ", len(r.Data.(model.Audits)))
}
store.Must(ss.Audit().PermanentDeleteBatch(cutoff, 1000000))
if r := <-ss.Audit().Get(a1.UserId, 0, 100); len(r.Data.(model.Audits)) != 1 {
t.Fatal("Expected 1 audit. Got ", len(r.Data.(model.Audits)))
}
if r2 := <-ss.Audit().PermanentDeleteByUser(a1.UserId); r2.Err != nil {
t.Fatal(r2.Err)
}
}

1967
store/storetest/channel_store.go Обычный файл

Разница между файлами не показана из-за своего большого размера Загрузить разницу

200
store/storetest/cluster_discovery_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,200 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"time"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestClusterDiscoveryStore(t *testing.T, ss store.Store) {
t.Run("", func(t *testing.T) { testClusterDiscoveryStore(t, ss) })
t.Run("Delete", func(t *testing.T) { testClusterDiscoveryStoreDelete(t, ss) })
t.Run("LastPing", func(t *testing.T) { testClusterDiscoveryStoreLastPing(t, ss) })
t.Run("Exists", func(t *testing.T) { testClusterDiscoveryStoreExists(t, ss) })
t.Run("ClusterDiscoveryGetStore", func(t *testing.T) { testClusterDiscoveryGetStore(t, ss) })
}
func testClusterDiscoveryStore(t *testing.T, ss store.Store) {
discovery := &model.ClusterDiscovery{
ClusterName: "cluster_name",
Hostname: "hostname" + model.NewId(),
Type: "test_test",
}
if result := <-ss.ClusterDiscovery().Save(discovery); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.ClusterDiscovery().Cleanup(); result.Err != nil {
t.Fatal(result.Err)
}
}
func testClusterDiscoveryStoreDelete(t *testing.T, ss store.Store) {
discovery := &model.ClusterDiscovery{
ClusterName: "cluster_name",
Hostname: "hostname" + model.NewId(),
Type: "test_test",
}
if result := <-ss.ClusterDiscovery().Save(discovery); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.ClusterDiscovery().Delete(discovery); result.Err != nil {
t.Fatal(result.Err)
}
}
func testClusterDiscoveryStoreLastPing(t *testing.T, ss store.Store) {
discovery := &model.ClusterDiscovery{
ClusterName: "cluster_name_lastPing",
Hostname: "hostname" + model.NewId(),
Type: "test_test_lastPing" + model.NewId(),
}
if result := <-ss.ClusterDiscovery().Save(discovery); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.ClusterDiscovery().SetLastPingAt(discovery); result.Err != nil {
t.Fatal(result.Err)
}
ttime := model.GetMillis()
time.Sleep(1 * time.Second)
if result := <-ss.ClusterDiscovery().SetLastPingAt(discovery); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.ClusterDiscovery().GetAll(discovery.Type, "cluster_name_lastPing"); result.Err != nil {
t.Fatal(result.Err)
} else {
list := result.Data.([]*model.ClusterDiscovery)
if len(list) != 1 {
t.Fatal("should only be 1 items")
return
}
if list[0].LastPingAt-ttime < 500 {
t.Fatal("failed to set time")
}
}
discovery2 := &model.ClusterDiscovery{
ClusterName: "cluster_name_missing",
Hostname: "hostname" + model.NewId(),
Type: "test_test_missing",
}
if result := <-ss.ClusterDiscovery().SetLastPingAt(discovery2); result.Err != nil {
t.Fatal(result.Err)
}
}
func testClusterDiscoveryStoreExists(t *testing.T, ss store.Store) {
discovery := &model.ClusterDiscovery{
ClusterName: "cluster_name_Exists",
Hostname: "hostname" + model.NewId(),
Type: "test_test_Exists" + model.NewId(),
}
if result := <-ss.ClusterDiscovery().Save(discovery); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.ClusterDiscovery().Exists(discovery); result.Err != nil {
t.Fatal(result.Err)
} else {
val := result.Data.(bool)
if !val {
t.Fatal("should be true")
}
}
discovery.ClusterName = "cluster_name_Exists2"
if result := <-ss.ClusterDiscovery().Exists(discovery); result.Err != nil {
t.Fatal(result.Err)
} else {
val := result.Data.(bool)
if val {
t.Fatal("should be true")
}
}
}
func testClusterDiscoveryGetStore(t *testing.T, ss store.Store) {
testType1 := model.NewId()
discovery1 := &model.ClusterDiscovery{
ClusterName: "cluster_name",
Hostname: "hostname1",
Type: testType1,
}
store.Must(ss.ClusterDiscovery().Save(discovery1))
discovery2 := &model.ClusterDiscovery{
ClusterName: "cluster_name",
Hostname: "hostname2",
Type: testType1,
}
store.Must(ss.ClusterDiscovery().Save(discovery2))
discovery3 := &model.ClusterDiscovery{
ClusterName: "cluster_name",
Hostname: "hostname3",
Type: testType1,
CreateAt: 1,
LastPingAt: 1,
}
store.Must(ss.ClusterDiscovery().Save(discovery3))
testType2 := model.NewId()
discovery4 := &model.ClusterDiscovery{
ClusterName: "cluster_name",
Hostname: "hostname1",
Type: testType2,
}
store.Must(ss.ClusterDiscovery().Save(discovery4))
if result := <-ss.ClusterDiscovery().GetAll(testType1, "cluster_name"); result.Err != nil {
t.Fatal(result.Err)
} else {
list := result.Data.([]*model.ClusterDiscovery)
if len(list) != 2 {
t.Fatal("Should only have returned 2")
}
}
if result := <-ss.ClusterDiscovery().GetAll(testType2, "cluster_name"); result.Err != nil {
t.Fatal(result.Err)
} else {
list := result.Data.([]*model.ClusterDiscovery)
if len(list) != 1 {
t.Fatal("Should only have returned 1")
}
}
if result := <-ss.ClusterDiscovery().GetAll(model.NewId(), "cluster_name"); result.Err != nil {
t.Fatal(result.Err)
} else {
list := result.Data.([]*model.ClusterDiscovery)
if len(list) != 0 {
t.Fatal("shouldn't be any")
}
}
}

251
store/storetest/command_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,251 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestCommandStore(t *testing.T, ss store.Store) {
t.Run("Save", func(t *testing.T) { testCommandStoreSave(t, ss) })
t.Run("Get", func(t *testing.T) { testCommandStoreGet(t, ss) })
t.Run("GetByTeam", func(t *testing.T) { testCommandStoreGetByTeam(t, ss) })
t.Run("GetByTrigger", func(t *testing.T) { testCommandStoreGetByTrigger(t, ss) })
t.Run("Delete", func(t *testing.T) { testCommandStoreDelete(t, ss) })
t.Run("DeleteByTeam", func(t *testing.T) { testCommandStoreDeleteByTeam(t, ss) })
t.Run("DeleteByUser", func(t *testing.T) { testCommandStoreDeleteByUser(t, ss) })
t.Run("Update", func(t *testing.T) { testCommandStoreUpdate(t, ss) })
t.Run("CommandCount", func(t *testing.T) { testCommandCount(t, ss) })
}
func testCommandStoreSave(t *testing.T, ss store.Store) {
o1 := model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger"
if err := (<-ss.Command().Save(&o1)).Err; err != nil {
t.Fatal("couldn't save item", err)
}
if err := (<-ss.Command().Save(&o1)).Err; err == nil {
t.Fatal("shouldn't be able to update from save")
}
}
func testCommandStoreGet(t *testing.T, ss store.Store) {
o1 := &model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger"
o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-ss.Command().Get(o1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.Command).CreateAt != o1.CreateAt {
t.Fatal("invalid returned command")
}
}
if err := (<-ss.Command().Get("123")).Err; err == nil {
t.Fatal("Missing id should have failed")
}
}
func testCommandStoreGetByTeam(t *testing.T, ss store.Store) {
o1 := &model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger"
o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-ss.Command().GetByTeam(o1.TeamId); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.([]*model.Command)[0].CreateAt != o1.CreateAt {
t.Fatal("invalid returned command")
}
}
if result := <-ss.Command().GetByTeam("123"); result.Err != nil {
t.Fatal(result.Err)
} else {
if len(result.Data.([]*model.Command)) != 0 {
t.Fatal("no commands should have returned")
}
}
}
func testCommandStoreGetByTrigger(t *testing.T, ss store.Store) {
o1 := &model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger1"
o2 := &model.Command{}
o2.CreatorId = model.NewId()
o2.Method = model.COMMAND_METHOD_POST
o2.TeamId = model.NewId()
o2.URL = "http://nowhere.com/"
o2.Trigger = "trigger1"
o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
o2 = (<-ss.Command().Save(o2)).Data.(*model.Command)
if r1 := <-ss.Command().GetByTrigger(o1.TeamId, o1.Trigger); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.Command).Id != o1.Id {
t.Fatal("invalid returned command")
}
}
store.Must(ss.Command().Delete(o1.Id, model.GetMillis()))
if result := <-ss.Command().GetByTrigger(o1.TeamId, o1.Trigger); result.Err == nil {
t.Fatal("no commands should have returned")
}
}
func testCommandStoreDelete(t *testing.T, ss store.Store) {
o1 := &model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger"
o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-ss.Command().Get(o1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.Command).CreateAt != o1.CreateAt {
t.Fatal("invalid returned command")
}
}
if r2 := <-ss.Command().Delete(o1.Id, model.GetMillis()); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Command().Get(o1.Id)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func testCommandStoreDeleteByTeam(t *testing.T, ss store.Store) {
o1 := &model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger"
o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-ss.Command().Get(o1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.Command).CreateAt != o1.CreateAt {
t.Fatal("invalid returned command")
}
}
if r2 := <-ss.Command().PermanentDeleteByTeam(o1.TeamId); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Command().Get(o1.Id)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func testCommandStoreDeleteByUser(t *testing.T, ss store.Store) {
o1 := &model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger"
o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-ss.Command().Get(o1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.Command).CreateAt != o1.CreateAt {
t.Fatal("invalid returned command")
}
}
if r2 := <-ss.Command().PermanentDeleteByUser(o1.CreatorId); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Command().Get(o1.Id)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func testCommandStoreUpdate(t *testing.T, ss store.Store) {
o1 := &model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger"
o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
o1.Token = model.NewId()
if r2 := <-ss.Command().Update(o1); r2.Err != nil {
t.Fatal(r2.Err)
}
}
func testCommandCount(t *testing.T, ss store.Store) {
o1 := &model.Command{}
o1.CreatorId = model.NewId()
o1.Method = model.COMMAND_METHOD_POST
o1.TeamId = model.NewId()
o1.URL = "http://nowhere.com/"
o1.Trigger = "trigger"
o1 = (<-ss.Command().Save(o1)).Data.(*model.Command)
if r1 := <-ss.Command().AnalyticsCommandCount(""); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(int64) == 0 {
t.Fatal("should be at least 1 command")
}
}
if r2 := <-ss.Command().AnalyticsCommandCount(o1.TeamId); r2.Err != nil {
t.Fatal(r2.Err)
} else {
if r2.Data.(int64) != 1 {
t.Fatal("should be 1 command")
}
}
}

68
store/storetest/command_webhook_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,68 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"net/http"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestCommandWebhookStore(t *testing.T, ss store.Store) {
t.Run("", func(t *testing.T) { testCommandWebhookStore(t, ss) })
}
func testCommandWebhookStore(t *testing.T, ss store.Store) {
cws := ss.CommandWebhook()
h1 := &model.CommandWebhook{}
h1.CommandId = model.NewId()
h1.UserId = model.NewId()
h1.ChannelId = model.NewId()
h1 = (<-cws.Save(h1)).Data.(*model.CommandWebhook)
if r1 := <-cws.Get(h1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if *r1.Data.(*model.CommandWebhook) != *h1 {
t.Fatal("invalid returned webhook")
}
}
if err := (<-cws.Get("123")).Err; err.StatusCode != http.StatusNotFound {
t.Fatal("Should have set the status as not found for missing id")
}
h2 := &model.CommandWebhook{}
h2.CreateAt = model.GetMillis() - 2*model.COMMAND_WEBHOOK_LIFETIME
h2.CommandId = model.NewId()
h2.UserId = model.NewId()
h2.ChannelId = model.NewId()
h2 = (<-cws.Save(h2)).Data.(*model.CommandWebhook)
if err := (<-cws.Get(h2.Id)).Err; err == nil || err.StatusCode != http.StatusNotFound {
t.Fatal("Should have set the status as not found for expired webhook")
}
cws.Cleanup()
if err := (<-cws.Get(h1.Id)).Err; err != nil {
t.Fatal("Should have no error getting unexpired webhook")
}
if err := (<-cws.Get(h2.Id)).Err; err.StatusCode != http.StatusNotFound {
t.Fatal("Should have set the status as not found for expired webhook")
}
if err := (<-cws.TryUse(h1.Id, 1)).Err; err != nil {
t.Fatal("Should be able to use webhook once")
}
if err := (<-cws.TryUse(h1.Id, 1)).Err; err == nil || err.StatusCode != http.StatusBadRequest {
t.Fatal("Should be able to use webhook once")
}
}

318
store/storetest/compliance_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,318 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"time"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestComplianceStore(t *testing.T, ss store.Store) {
t.Run("", func(t *testing.T) { testComplianceStore(t, ss) })
t.Run("ComplianceExport", func(t *testing.T) { testComplianceExport(t, ss) })
t.Run("ComplianceExportDirectMessages", func(t *testing.T) { testComplianceExportDirectMessages(t, ss) })
}
func testComplianceStore(t *testing.T, ss store.Store) {
compliance1 := &model.Compliance{Desc: "Audit for federal subpoena case #22443", UserId: model.NewId(), Status: model.COMPLIANCE_STATUS_FAILED, StartAt: model.GetMillis() - 1, EndAt: model.GetMillis() + 1, Type: model.COMPLIANCE_TYPE_ADHOC}
store.Must(ss.Compliance().Save(compliance1))
time.Sleep(100 * time.Millisecond)
compliance2 := &model.Compliance{Desc: "Audit for federal subpoena case #11458", UserId: model.NewId(), Status: model.COMPLIANCE_STATUS_RUNNING, StartAt: model.GetMillis() - 1, EndAt: model.GetMillis() + 1, Type: model.COMPLIANCE_TYPE_ADHOC}
store.Must(ss.Compliance().Save(compliance2))
time.Sleep(100 * time.Millisecond)
c := ss.Compliance().GetAll(0, 1000)
result := <-c
compliances := result.Data.(model.Compliances)
if compliances[0].Status != model.COMPLIANCE_STATUS_RUNNING && compliance2.Id != compliances[0].Id {
t.Fatal()
}
compliance2.Status = model.COMPLIANCE_STATUS_FAILED
store.Must(ss.Compliance().Update(compliance2))
c = ss.Compliance().GetAll(0, 1000)
result = <-c
compliances = result.Data.(model.Compliances)
if compliances[0].Status != model.COMPLIANCE_STATUS_FAILED && compliance2.Id != compliances[0].Id {
t.Fatal()
}
c = ss.Compliance().GetAll(0, 1)
result = <-c
compliances = result.Data.(model.Compliances)
if len(compliances) != 1 {
t.Fatal("should only have returned 1")
}
c = ss.Compliance().GetAll(1, 1)
result = <-c
compliances = result.Data.(model.Compliances)
if len(compliances) != 1 {
t.Fatal("should only have returned 1")
}
rc2 := (<-ss.Compliance().Get(compliance2.Id)).Data.(*model.Compliance)
if rc2.Status != compliance2.Status {
t.Fatal()
}
}
func testComplianceExport(t *testing.T, ss store.Store) {
time.Sleep(100 * time.Millisecond)
t1 := &model.Team{}
t1.DisplayName = "DisplayName"
t1.Name = "zz" + model.NewId() + "b"
t1.Email = model.NewId() + "@nowhere.com"
t1.Type = model.TEAM_OPEN
t1 = store.Must(ss.Team().Save(t1)).(*model.Team)
u1 := &model.User{}
u1.Email = model.NewId()
u1.Username = model.NewId()
u1 = store.Must(ss.User().Save(u1)).(*model.User)
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: t1.Id, UserId: u1.Id}))
u2 := &model.User{}
u2.Email = model.NewId()
u2.Username = model.NewId()
u2 = store.Must(ss.User().Save(u2)).(*model.User)
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: t1.Id, UserId: u2.Id}))
c1 := &model.Channel{}
c1.TeamId = t1.Id
c1.DisplayName = "Channel2"
c1.Name = "zz" + model.NewId() + "b"
c1.Type = model.CHANNEL_OPEN
c1 = store.Must(ss.Channel().Save(c1)).(*model.Channel)
o1 := &model.Post{}
o1.ChannelId = c1.Id
o1.UserId = u1.Id
o1.CreateAt = model.GetMillis()
o1.Message = "zz" + model.NewId() + "b"
o1 = store.Must(ss.Post().Save(o1)).(*model.Post)
o1a := &model.Post{}
o1a.ChannelId = c1.Id
o1a.UserId = u1.Id
o1a.CreateAt = o1.CreateAt + 10
o1a.Message = "zz" + model.NewId() + "b"
o1a = store.Must(ss.Post().Save(o1a)).(*model.Post)
o2 := &model.Post{}
o2.ChannelId = c1.Id
o2.UserId = u1.Id
o2.CreateAt = o1.CreateAt + 20
o2.Message = "zz" + model.NewId() + "b"
o2 = store.Must(ss.Post().Save(o2)).(*model.Post)
o2a := &model.Post{}
o2a.ChannelId = c1.Id
o2a.UserId = u2.Id
o2a.CreateAt = o1.CreateAt + 30
o2a.Message = "zz" + model.NewId() + "b"
o2a = store.Must(ss.Post().Save(o2a)).(*model.Post)
time.Sleep(100 * time.Millisecond)
cr1 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1}
if r1 := <-ss.Compliance().ComplianceExport(cr1); r1.Err != nil {
t.Fatal(r1.Err)
} else {
cposts := r1.Data.([]*model.CompliancePost)
if len(cposts) != 4 {
t.Fatal("return wrong results length")
}
if cposts[0].PostId != o1.Id {
t.Fatal("Wrong sort")
}
if cposts[3].PostId != o2a.Id {
t.Fatal("Wrong sort")
}
}
cr2 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Emails: u2.Email}
if r1 := <-ss.Compliance().ComplianceExport(cr2); r1.Err != nil {
t.Fatal(r1.Err)
} else {
cposts := r1.Data.([]*model.CompliancePost)
if len(cposts) != 1 {
t.Fatal("return wrong results length")
}
if cposts[0].PostId != o2a.Id {
t.Fatal("Wrong sort")
}
}
cr3 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Emails: u2.Email + ", " + u1.Email}
if r1 := <-ss.Compliance().ComplianceExport(cr3); r1.Err != nil {
t.Fatal(r1.Err)
} else {
cposts := r1.Data.([]*model.CompliancePost)
if len(cposts) != 4 {
t.Fatal("return wrong results length")
}
if cposts[0].PostId != o1.Id {
t.Fatal("Wrong sort")
}
if cposts[3].PostId != o2a.Id {
t.Fatal("Wrong sort")
}
}
cr4 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Keywords: o2a.Message}
if r1 := <-ss.Compliance().ComplianceExport(cr4); r1.Err != nil {
t.Fatal(r1.Err)
} else {
cposts := r1.Data.([]*model.CompliancePost)
if len(cposts) != 1 {
t.Fatal("return wrong results length")
}
if cposts[0].PostId != o2a.Id {
t.Fatal("Wrong sort")
}
}
cr5 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Keywords: o2a.Message + " " + o1.Message}
if r1 := <-ss.Compliance().ComplianceExport(cr5); r1.Err != nil {
t.Fatal(r1.Err)
} else {
cposts := r1.Data.([]*model.CompliancePost)
if len(cposts) != 2 {
t.Fatal("return wrong results length")
}
if cposts[0].PostId != o1.Id {
t.Fatal("Wrong sort")
}
}
cr6 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o2a.CreateAt + 1, Emails: u2.Email + ", " + u1.Email, Keywords: o2a.Message + " " + o1.Message}
if r1 := <-ss.Compliance().ComplianceExport(cr6); r1.Err != nil {
t.Fatal(r1.Err)
} else {
cposts := r1.Data.([]*model.CompliancePost)
if len(cposts) != 2 {
t.Fatal("return wrong results length")
}
if cposts[0].PostId != o1.Id {
t.Fatal("Wrong sort")
}
if cposts[1].PostId != o2a.Id {
t.Fatal("Wrong sort")
}
}
}
func testComplianceExportDirectMessages(t *testing.T, ss store.Store) {
time.Sleep(100 * time.Millisecond)
t1 := &model.Team{}
t1.DisplayName = "DisplayName"
t1.Name = "zz" + model.NewId() + "b"
t1.Email = model.NewId() + "@nowhere.com"
t1.Type = model.TEAM_OPEN
t1 = store.Must(ss.Team().Save(t1)).(*model.Team)
u1 := &model.User{}
u1.Email = model.NewId()
u1.Username = model.NewId()
u1 = store.Must(ss.User().Save(u1)).(*model.User)
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: t1.Id, UserId: u1.Id}))
u2 := &model.User{}
u2.Email = model.NewId()
u2.Username = model.NewId()
u2 = store.Must(ss.User().Save(u2)).(*model.User)
store.Must(ss.Team().SaveMember(&model.TeamMember{TeamId: t1.Id, UserId: u2.Id}))
c1 := &model.Channel{}
c1.TeamId = t1.Id
c1.DisplayName = "Channel2"
c1.Name = "zz" + model.NewId() + "b"
c1.Type = model.CHANNEL_OPEN
c1 = store.Must(ss.Channel().Save(c1)).(*model.Channel)
cDM := store.Must(ss.Channel().CreateDirectChannel(u1.Id, u2.Id)).(*model.Channel)
o1 := &model.Post{}
o1.ChannelId = c1.Id
o1.UserId = u1.Id
o1.CreateAt = model.GetMillis()
o1.Message = "zz" + model.NewId() + "b"
o1 = store.Must(ss.Post().Save(o1)).(*model.Post)
o1a := &model.Post{}
o1a.ChannelId = c1.Id
o1a.UserId = u1.Id
o1a.CreateAt = o1.CreateAt + 10
o1a.Message = "zz" + model.NewId() + "b"
o1a = store.Must(ss.Post().Save(o1a)).(*model.Post)
o2 := &model.Post{}
o2.ChannelId = c1.Id
o2.UserId = u1.Id
o2.CreateAt = o1.CreateAt + 20
o2.Message = "zz" + model.NewId() + "b"
o2 = store.Must(ss.Post().Save(o2)).(*model.Post)
o2a := &model.Post{}
o2a.ChannelId = c1.Id
o2a.UserId = u2.Id
o2a.CreateAt = o1.CreateAt + 30
o2a.Message = "zz" + model.NewId() + "b"
o2a = store.Must(ss.Post().Save(o2a)).(*model.Post)
o3 := &model.Post{}
o3.ChannelId = cDM.Id
o3.UserId = u1.Id
o3.CreateAt = o1.CreateAt + 40
o3.Message = "zz" + model.NewId() + "b"
o3 = store.Must(ss.Post().Save(o3)).(*model.Post)
time.Sleep(100 * time.Millisecond)
cr1 := &model.Compliance{Desc: "test" + model.NewId(), StartAt: o1.CreateAt - 1, EndAt: o3.CreateAt + 1, Emails: u1.Email}
if r1 := <-ss.Compliance().ComplianceExport(cr1); r1.Err != nil {
t.Fatal(r1.Err)
} else {
cposts := r1.Data.([]*model.CompliancePost)
if len(cposts) != 4 {
t.Fatal("return wrong results length")
}
if cposts[0].PostId != o1.Id {
t.Fatal("Wrong sort")
}
if cposts[len(cposts)-1].PostId != o3.Id {
t.Fatal("Wrong sort")
}
}
}

175
store/storetest/emoji_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,175 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"time"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestEmojiStore(t *testing.T, ss store.Store) {
t.Run("EmojiSaveDelete", func(t *testing.T) { testEmojiSaveDelete(t, ss) })
t.Run("EmojiGet", func(t *testing.T) { testEmojiGet(t, ss) })
t.Run("EmojiGetByName", func(t *testing.T) { testEmojiGetByName(t, ss) })
t.Run("EmojiGetList", func(t *testing.T) { testEmojiGetList(t, ss) })
}
func testEmojiSaveDelete(t *testing.T, ss store.Store) {
emoji1 := &model.Emoji{
CreatorId: model.NewId(),
Name: model.NewId(),
}
if result := <-ss.Emoji().Save(emoji1); result.Err != nil {
t.Fatal(result.Err)
}
if len(emoji1.Id) != 26 {
t.Fatal("should've set id for emoji")
}
emoji2 := model.Emoji{
CreatorId: model.NewId(),
Name: emoji1.Name,
}
if result := <-ss.Emoji().Save(&emoji2); result.Err == nil {
t.Fatal("shouldn't be able to save emoji with duplicate name")
}
if result := <-ss.Emoji().Delete(emoji1.Id, time.Now().Unix()); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.Emoji().Save(&emoji2); result.Err != nil {
t.Fatal("should be able to save emoji with duplicate name now that original has been deleted", result.Err)
}
if result := <-ss.Emoji().Delete(emoji2.Id, time.Now().Unix()+1); result.Err != nil {
t.Fatal(result.Err)
}
}
func testEmojiGet(t *testing.T, ss store.Store) {
emojis := []model.Emoji{
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
}
for i, emoji := range emojis {
emojis[i] = *store.Must(ss.Emoji().Save(&emoji)).(*model.Emoji)
}
defer func() {
for _, emoji := range emojis {
store.Must(ss.Emoji().Delete(emoji.Id, time.Now().Unix()))
}
}()
for _, emoji := range emojis {
if result := <-ss.Emoji().Get(emoji.Id, false); result.Err != nil {
t.Fatalf("failed to get emoji with id %v: %v", emoji.Id, result.Err)
}
}
for _, emoji := range emojis {
if result := <-ss.Emoji().Get(emoji.Id, true); result.Err != nil {
t.Fatalf("failed to get emoji with id %v: %v", emoji.Id, result.Err)
}
}
for _, emoji := range emojis {
if result := <-ss.Emoji().Get(emoji.Id, true); result.Err != nil {
t.Fatalf("failed to get emoji with id %v: %v", emoji.Id, result.Err)
}
}
}
func testEmojiGetByName(t *testing.T, ss store.Store) {
emojis := []model.Emoji{
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
}
for i, emoji := range emojis {
emojis[i] = *store.Must(ss.Emoji().Save(&emoji)).(*model.Emoji)
}
defer func() {
for _, emoji := range emojis {
store.Must(ss.Emoji().Delete(emoji.Id, time.Now().Unix()))
}
}()
for _, emoji := range emojis {
if result := <-ss.Emoji().GetByName(emoji.Name); result.Err != nil {
t.Fatalf("failed to get emoji with name %v: %v", emoji.Name, result.Err)
}
}
}
func testEmojiGetList(t *testing.T, ss store.Store) {
emojis := []model.Emoji{
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
{
CreatorId: model.NewId(),
Name: model.NewId(),
},
}
for i, emoji := range emojis {
emojis[i] = *store.Must(ss.Emoji().Save(&emoji)).(*model.Emoji)
}
defer func() {
for _, emoji := range emojis {
store.Must(ss.Emoji().Delete(emoji.Id, time.Now().Unix()))
}
}()
if result := <-ss.Emoji().GetList(0, 100); result.Err != nil {
t.Fatal(result.Err)
} else {
for _, emoji := range emojis {
found := false
for _, savedEmoji := range result.Data.([]*model.Emoji) {
if emoji.Id == savedEmoji.Id {
found = true
break
}
}
if !found {
t.Fatalf("failed to get emoji with id %v", emoji.Id)
}
}
}
}

296
store/storetest/file_info_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,296 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"fmt"
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestFileInfoStore(t *testing.T, ss store.Store) {
t.Run("FileInfoSaveGet", func(t *testing.T) { testFileInfoSaveGet(t, ss) })
t.Run("FileInfoSaveGetByPath", func(t *testing.T) { testFileInfoSaveGetByPath(t, ss) })
t.Run("FileInfoGetForPost", func(t *testing.T) { testFileInfoGetForPost(t, ss) })
t.Run("FileInfoAttachToPost", func(t *testing.T) { testFileInfoAttachToPost(t, ss) })
t.Run("FileInfoDeleteForPost", func(t *testing.T) { testFileInfoDeleteForPost(t, ss) })
t.Run("FileInfoPermanentDelete", func(t *testing.T) { testFileInfoPermanentDelete(t, ss) })
t.Run("FileInfoPermanentDeleteBatch", func(t *testing.T) { testFileInfoPermanentDeleteBatch(t, ss) })
}
func testFileInfoSaveGet(t *testing.T, ss store.Store) {
info := &model.FileInfo{
CreatorId: model.NewId(),
Path: "file.txt",
}
if result := <-ss.FileInfo().Save(info); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.(*model.FileInfo); len(returned.Id) == 0 {
t.Fatal("should've assigned an id to FileInfo")
} else {
info = returned
}
defer func() {
<-ss.FileInfo().PermanentDelete(info.Id)
}()
if result := <-ss.FileInfo().Get(info.Id); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.(*model.FileInfo); returned.Id != info.Id {
t.Log(info)
t.Log(returned)
t.Fatal("should've returned correct FileInfo")
}
info2 := store.Must(ss.FileInfo().Save(&model.FileInfo{
CreatorId: model.NewId(),
Path: "file.txt",
DeleteAt: 123,
})).(*model.FileInfo)
if result := <-ss.FileInfo().Get(info2.Id); result.Err == nil {
t.Fatal("shouldn't have gotten deleted file")
}
defer func() {
<-ss.FileInfo().PermanentDelete(info2.Id)
}()
}
func testFileInfoSaveGetByPath(t *testing.T, ss store.Store) {
info := &model.FileInfo{
CreatorId: model.NewId(),
Path: fmt.Sprintf("%v/file.txt", model.NewId()),
}
if result := <-ss.FileInfo().Save(info); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.(*model.FileInfo); len(returned.Id) == 0 {
t.Fatal("should've assigned an id to FileInfo")
} else {
info = returned
}
defer func() {
<-ss.FileInfo().PermanentDelete(info.Id)
}()
if result := <-ss.FileInfo().GetByPath(info.Path); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.(*model.FileInfo); returned.Id != info.Id {
t.Log(info)
t.Log(returned)
t.Fatal("should've returned correct FileInfo")
}
info2 := store.Must(ss.FileInfo().Save(&model.FileInfo{
CreatorId: model.NewId(),
Path: "file.txt",
DeleteAt: 123,
})).(*model.FileInfo)
if result := <-ss.FileInfo().GetByPath(info2.Id); result.Err == nil {
t.Fatal("shouldn't have gotten deleted file")
}
defer func() {
<-ss.FileInfo().PermanentDelete(info2.Id)
}()
}
func testFileInfoGetForPost(t *testing.T, ss store.Store) {
userId := model.NewId()
postId := model.NewId()
infos := []*model.FileInfo{
{
PostId: postId,
CreatorId: userId,
Path: "file.txt",
},
{
PostId: postId,
CreatorId: userId,
Path: "file.txt",
},
{
PostId: postId,
CreatorId: userId,
Path: "file.txt",
DeleteAt: 123,
},
{
PostId: model.NewId(),
CreatorId: userId,
Path: "file.txt",
},
}
for i, info := range infos {
infos[i] = store.Must(ss.FileInfo().Save(info)).(*model.FileInfo)
defer func(id string) {
<-ss.FileInfo().PermanentDelete(id)
}(infos[i].Id)
}
if result := <-ss.FileInfo().GetForPost(postId, true, false); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.([]*model.FileInfo); len(returned) != 2 {
t.Fatal("should've returned exactly 2 file infos")
}
if result := <-ss.FileInfo().GetForPost(postId, false, false); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.([]*model.FileInfo); len(returned) != 2 {
t.Fatal("should've returned exactly 2 file infos")
}
if result := <-ss.FileInfo().GetForPost(postId, true, true); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.([]*model.FileInfo); len(returned) != 2 {
t.Fatal("should've returned exactly 2 file infos")
}
}
func testFileInfoAttachToPost(t *testing.T, ss store.Store) {
userId := model.NewId()
postId := model.NewId()
info1 := store.Must(ss.FileInfo().Save(&model.FileInfo{
CreatorId: userId,
Path: "file.txt",
})).(*model.FileInfo)
defer func() {
<-ss.FileInfo().PermanentDelete(info1.Id)
}()
if len(info1.PostId) != 0 {
t.Fatal("file shouldn't have a PostId")
}
if result := <-ss.FileInfo().AttachToPost(info1.Id, postId); result.Err != nil {
t.Fatal(result.Err)
} else {
info1 = store.Must(ss.FileInfo().Get(info1.Id)).(*model.FileInfo)
}
if len(info1.PostId) == 0 {
t.Fatal("file should now have a PostId")
}
info2 := store.Must(ss.FileInfo().Save(&model.FileInfo{
CreatorId: userId,
Path: "file.txt",
})).(*model.FileInfo)
defer func() {
<-ss.FileInfo().PermanentDelete(info2.Id)
}()
if result := <-ss.FileInfo().AttachToPost(info2.Id, postId); result.Err != nil {
t.Fatal(result.Err)
} else {
info2 = store.Must(ss.FileInfo().Get(info2.Id)).(*model.FileInfo)
}
if result := <-ss.FileInfo().GetForPost(postId, true, false); result.Err != nil {
t.Fatal(result.Err)
} else if infos := result.Data.([]*model.FileInfo); len(infos) != 2 {
t.Fatal("should've returned exactly 2 file infos")
}
}
func testFileInfoDeleteForPost(t *testing.T, ss store.Store) {
userId := model.NewId()
postId := model.NewId()
infos := []*model.FileInfo{
{
PostId: postId,
CreatorId: userId,
Path: "file.txt",
},
{
PostId: postId,
CreatorId: userId,
Path: "file.txt",
},
{
PostId: postId,
CreatorId: userId,
Path: "file.txt",
DeleteAt: 123,
},
{
PostId: model.NewId(),
CreatorId: userId,
Path: "file.txt",
},
}
for i, info := range infos {
infos[i] = store.Must(ss.FileInfo().Save(info)).(*model.FileInfo)
defer func(id string) {
<-ss.FileInfo().PermanentDelete(id)
}(infos[i].Id)
}
if result := <-ss.FileInfo().DeleteForPost(postId); result.Err != nil {
t.Fatal(result.Err)
}
if infos := store.Must(ss.FileInfo().GetForPost(postId, true, false)).([]*model.FileInfo); len(infos) != 0 {
t.Fatal("shouldn't have returned any file infos")
}
}
func testFileInfoPermanentDelete(t *testing.T, ss store.Store) {
info := store.Must(ss.FileInfo().Save(&model.FileInfo{
PostId: model.NewId(),
CreatorId: model.NewId(),
Path: "file.txt",
})).(*model.FileInfo)
if result := <-ss.FileInfo().PermanentDelete(info.Id); result.Err != nil {
t.Fatal(result.Err)
}
}
func testFileInfoPermanentDeleteBatch(t *testing.T, ss store.Store) {
postId := model.NewId()
store.Must(ss.FileInfo().Save(&model.FileInfo{
PostId: postId,
CreatorId: model.NewId(),
Path: "file.txt",
CreateAt: 1000,
}))
store.Must(ss.FileInfo().Save(&model.FileInfo{
PostId: postId,
CreatorId: model.NewId(),
Path: "file.txt",
CreateAt: 1200,
}))
store.Must(ss.FileInfo().Save(&model.FileInfo{
PostId: postId,
CreatorId: model.NewId(),
Path: "file.txt",
CreateAt: 2000,
}))
if result := <-ss.FileInfo().GetForPost(postId, true, false); result.Err != nil {
t.Fatal(result.Err)
} else if len(result.Data.([]*model.FileInfo)) != 3 {
t.Fatal("Expected 3 fileInfos")
}
store.Must(ss.FileInfo().PermanentDeleteBatch(1500, 1000))
if result := <-ss.FileInfo().GetForPost(postId, true, false); result.Err != nil {
t.Fatal(result.Err)
} else if len(result.Data.([]*model.FileInfo)) != 1 {
t.Fatal("Expected 3 fileInfos")
}
}

507
store/storetest/job_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,507 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"time"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
"github.com/stretchr/testify/assert"
)
func TestJobStore(t *testing.T, ss store.Store) {
t.Run("JobSaveGet", func(t *testing.T) { testJobSaveGet(t, ss) })
t.Run("JobGetAllByType", func(t *testing.T) { testJobGetAllByType(t, ss) })
t.Run("JobGetAllByTypePage", func(t *testing.T) { testJobGetAllByTypePage(t, ss) })
t.Run("JobGetAllPage", func(t *testing.T) { testJobGetAllPage(t, ss) })
t.Run("JobGetAllByStatus", func(t *testing.T) { testJobGetAllByStatus(t, ss) })
t.Run("GetNewestJobByStatusAndType", func(t *testing.T) { testJobStoreGetNewestJobByStatusAndType(t, ss) })
t.Run("GetCountByStatusAndType", func(t *testing.T) { testJobStoreGetCountByStatusAndType(t, ss) })
t.Run("JobUpdateOptimistically", func(t *testing.T) { testJobUpdateOptimistically(t, ss) })
t.Run("JobUpdateStatusUpdateStatusOptimistically", func(t *testing.T) { testJobUpdateStatusUpdateStatusOptimistically(t, ss) })
t.Run("JobDelete", func(t *testing.T) { testJobDelete(t, ss) })
}
func testJobSaveGet(t *testing.T, ss store.Store) {
job := &model.Job{
Id: model.NewId(),
Type: model.NewId(),
Status: model.NewId(),
Data: map[string]string{
"Processed": "0",
"Total": "12345",
"LastProcessed": "abcd",
},
}
if result := <-ss.Job().Save(job); result.Err != nil {
t.Fatal(result.Err)
}
defer func() {
<-ss.Job().Delete(job.Id)
}()
if result := <-ss.Job().Get(job.Id); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.(*model.Job); received.Id != job.Id {
t.Fatal("received incorrect job after save")
} else if received.Data["Total"] != "12345" {
t.Fatal("data field was not retrieved successfully:", received.Data)
}
}
func testJobGetAllByType(t *testing.T, ss store.Store) {
jobType := model.NewId()
jobs := []*model.Job{
{
Id: model.NewId(),
Type: jobType,
},
{
Id: model.NewId(),
Type: jobType,
},
{
Id: model.NewId(),
Type: model.NewId(),
},
}
for _, job := range jobs {
store.Must(ss.Job().Save(job))
defer ss.Job().Delete(job.Id)
}
if result := <-ss.Job().GetAllByType(jobType); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) != 2 {
t.Fatal("received wrong number of jobs")
} else if received[0].Id != jobs[0].Id && received[1].Id != jobs[0].Id {
t.Fatal("should've received first jobs")
} else if received[0].Id != jobs[1].Id && received[1].Id != jobs[1].Id {
t.Fatal("should've received second jobs")
}
}
func testJobGetAllByTypePage(t *testing.T, ss store.Store) {
jobType := model.NewId()
jobs := []*model.Job{
{
Id: model.NewId(),
Type: jobType,
CreateAt: 1000,
},
{
Id: model.NewId(),
Type: jobType,
CreateAt: 999,
},
{
Id: model.NewId(),
Type: jobType,
CreateAt: 1001,
},
{
Id: model.NewId(),
Type: model.NewId(),
CreateAt: 1002,
},
}
for _, job := range jobs {
store.Must(ss.Job().Save(job))
defer ss.Job().Delete(job.Id)
}
if result := <-ss.Job().GetAllByTypePage(jobType, 0, 2); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) != 2 {
t.Fatal("received wrong number of jobs")
} else if received[0].Id != jobs[2].Id {
t.Fatal("should've received newest job first")
} else if received[1].Id != jobs[0].Id {
t.Fatal("should've received second newest job second")
}
if result := <-ss.Job().GetAllByTypePage(jobType, 2, 2); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) != 1 {
t.Fatal("received wrong number of jobs")
} else if received[0].Id != jobs[1].Id {
t.Fatal("should've received oldest job last")
}
}
func testJobGetAllPage(t *testing.T, ss store.Store) {
jobType := model.NewId()
createAtTime := model.GetMillis()
jobs := []*model.Job{
{
Id: model.NewId(),
Type: jobType,
CreateAt: createAtTime + 1,
},
{
Id: model.NewId(),
Type: jobType,
CreateAt: createAtTime,
},
{
Id: model.NewId(),
Type: jobType,
CreateAt: createAtTime + 2,
},
}
for _, job := range jobs {
store.Must(ss.Job().Save(job))
defer ss.Job().Delete(job.Id)
}
if result := <-ss.Job().GetAllPage(0, 2); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) != 2 {
t.Fatal("received wrong number of jobs")
} else if received[0].Id != jobs[2].Id {
t.Fatal("should've received newest job first")
} else if received[1].Id != jobs[0].Id {
t.Fatal("should've received second newest job second")
}
if result := <-ss.Job().GetAllPage(2, 2); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) < 1 {
t.Fatal("received wrong number of jobs")
} else if received[0].Id != jobs[1].Id {
t.Fatal("should've received oldest job last")
}
}
func testJobGetAllByStatus(t *testing.T, ss store.Store) {
jobType := model.NewId()
status := model.NewId()
jobs := []*model.Job{
{
Id: model.NewId(),
Type: jobType,
CreateAt: 1000,
Status: status,
Data: map[string]string{
"test": "data",
},
},
{
Id: model.NewId(),
Type: jobType,
CreateAt: 999,
Status: status,
},
{
Id: model.NewId(),
Type: jobType,
CreateAt: 1001,
Status: status,
},
{
Id: model.NewId(),
Type: jobType,
CreateAt: 1002,
Status: model.NewId(),
},
}
for _, job := range jobs {
store.Must(ss.Job().Save(job))
defer ss.Job().Delete(job.Id)
}
if result := <-ss.Job().GetAllByStatus(status); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.([]*model.Job); len(received) != 3 {
t.Fatal("received wrong number of jobs")
} else if received[0].Id != jobs[1].Id || received[1].Id != jobs[0].Id || received[2].Id != jobs[2].Id {
t.Fatal("should've received jobs ordered by CreateAt time")
} else if received[1].Data["test"] != "data" {
t.Fatal("should've received job data field back as saved")
}
}
func testJobStoreGetNewestJobByStatusAndType(t *testing.T, ss store.Store) {
jobType1 := model.NewId()
jobType2 := model.NewId()
status1 := model.NewId()
status2 := model.NewId()
jobs := []*model.Job{
{
Id: model.NewId(),
Type: jobType1,
CreateAt: 1001,
Status: status1,
},
{
Id: model.NewId(),
Type: jobType1,
CreateAt: 1000,
Status: status1,
},
{
Id: model.NewId(),
Type: jobType2,
CreateAt: 1003,
Status: status1,
},
{
Id: model.NewId(),
Type: jobType1,
CreateAt: 1004,
Status: status2,
},
}
for _, job := range jobs {
store.Must(ss.Job().Save(job))
defer ss.Job().Delete(job.Id)
}
result := <-ss.Job().GetNewestJobByStatusAndType(status1, jobType1)
assert.Nil(t, result.Err)
assert.EqualValues(t, jobs[0].Id, result.Data.(*model.Job).Id)
result = <-ss.Job().GetNewestJobByStatusAndType(model.NewId(), model.NewId())
assert.Nil(t, result.Err)
assert.Nil(t, result.Data.(*model.Job))
}
func testJobStoreGetCountByStatusAndType(t *testing.T, ss store.Store) {
jobType1 := model.NewId()
jobType2 := model.NewId()
status1 := model.NewId()
status2 := model.NewId()
jobs := []*model.Job{
{
Id: model.NewId(),
Type: jobType1,
CreateAt: 1000,
Status: status1,
},
{
Id: model.NewId(),
Type: jobType1,
CreateAt: 999,
Status: status1,
},
{
Id: model.NewId(),
Type: jobType2,
CreateAt: 1001,
Status: status1,
},
{
Id: model.NewId(),
Type: jobType1,
CreateAt: 1002,
Status: status2,
},
}
for _, job := range jobs {
store.Must(ss.Job().Save(job))
defer ss.Job().Delete(job.Id)
}
result := <-ss.Job().GetCountByStatusAndType(status1, jobType1)
assert.Nil(t, result.Err)
assert.EqualValues(t, 2, result.Data.(int64))
result = <-ss.Job().GetCountByStatusAndType(status2, jobType2)
assert.Nil(t, result.Err)
assert.EqualValues(t, 0, result.Data.(int64))
result = <-ss.Job().GetCountByStatusAndType(status1, jobType2)
assert.Nil(t, result.Err)
assert.EqualValues(t, 1, result.Data.(int64))
result = <-ss.Job().GetCountByStatusAndType(status2, jobType1)
assert.Nil(t, result.Err)
assert.EqualValues(t, 1, result.Data.(int64))
}
func testJobUpdateOptimistically(t *testing.T, ss store.Store) {
job := &model.Job{
Id: model.NewId(),
Type: model.JOB_TYPE_DATA_RETENTION,
CreateAt: model.GetMillis(),
Status: model.JOB_STATUS_PENDING,
}
if result := <-ss.Job().Save(job); result.Err != nil {
t.Fatal(result.Err)
}
defer ss.Job().Delete(job.Id)
job.LastActivityAt = model.GetMillis()
job.Status = model.JOB_STATUS_IN_PROGRESS
job.Progress = 50
job.Data = map[string]string{
"Foo": "Bar",
}
if result := <-ss.Job().UpdateOptimistically(job, model.JOB_STATUS_SUCCESS); result.Err != nil {
if result.Data.(bool) {
t.Fatal("should have failed due to incorrect old status")
}
}
time.Sleep(2 * time.Millisecond)
if result := <-ss.Job().UpdateOptimistically(job, model.JOB_STATUS_PENDING); result.Err != nil {
t.Fatal(result.Err)
} else {
if !result.Data.(bool) {
t.Fatal("Should have successfully updated")
}
var updatedJob *model.Job
if result := <-ss.Job().Get(job.Id); result.Err != nil {
t.Fatal(result.Err)
} else {
updatedJob = result.Data.(*model.Job)
}
if updatedJob.Type != job.Type || updatedJob.CreateAt != job.CreateAt || updatedJob.Status != job.Status || updatedJob.LastActivityAt <= job.LastActivityAt || updatedJob.Progress != job.Progress || updatedJob.Data["Foo"] != job.Data["Foo"] {
t.Fatal("Some update property was not as expected")
}
}
}
func testJobUpdateStatusUpdateStatusOptimistically(t *testing.T, ss store.Store) {
job := &model.Job{
Id: model.NewId(),
Type: model.JOB_TYPE_DATA_RETENTION,
CreateAt: model.GetMillis(),
Status: model.JOB_STATUS_SUCCESS,
}
var lastUpdateAt int64
if result := <-ss.Job().Save(job); result.Err != nil {
t.Fatal(result.Err)
} else {
lastUpdateAt = result.Data.(*model.Job).LastActivityAt
}
defer ss.Job().Delete(job.Id)
time.Sleep(2 * time.Millisecond)
if result := <-ss.Job().UpdateStatus(job.Id, model.JOB_STATUS_PENDING); result.Err != nil {
t.Fatal(result.Err)
} else {
received := result.Data.(*model.Job)
if received.Status != model.JOB_STATUS_PENDING {
t.Fatal("status wasn't updated")
}
if received.LastActivityAt <= lastUpdateAt {
t.Fatal("lastActivityAt wasn't updated")
}
lastUpdateAt = received.LastActivityAt
}
time.Sleep(2 * time.Millisecond)
if result := <-ss.Job().UpdateStatusOptimistically(job.Id, model.JOB_STATUS_IN_PROGRESS, model.JOB_STATUS_SUCCESS); result.Err != nil {
t.Fatal(result.Err)
} else {
if result.Data.(bool) {
t.Fatal("should be false due to incorrect original status")
}
}
if result := <-ss.Job().Get(job.Id); result.Err != nil {
t.Fatal(result.Err)
} else {
received := result.Data.(*model.Job)
if received.Status != model.JOB_STATUS_PENDING {
t.Fatal("should still be pending")
}
if received.LastActivityAt != lastUpdateAt {
t.Fatal("last activity at shouldn't have changed")
}
}
time.Sleep(2 * time.Millisecond)
if result := <-ss.Job().UpdateStatusOptimistically(job.Id, model.JOB_STATUS_PENDING, model.JOB_STATUS_IN_PROGRESS); result.Err != nil {
t.Fatal(result.Err)
} else {
if !result.Data.(bool) {
t.Fatal("should have succeeded")
}
}
var startAtSet int64
if result := <-ss.Job().Get(job.Id); result.Err != nil {
t.Fatal(result.Err)
} else {
received := result.Data.(*model.Job)
if received.Status != model.JOB_STATUS_IN_PROGRESS {
t.Fatal("should be in progress")
}
if received.StartAt == 0 {
t.Fatal("received should have start at set")
}
if received.LastActivityAt <= lastUpdateAt {
t.Fatal("lastActivityAt wasn't updated")
}
lastUpdateAt = received.LastActivityAt
startAtSet = received.StartAt
}
time.Sleep(2 * time.Millisecond)
if result := <-ss.Job().UpdateStatusOptimistically(job.Id, model.JOB_STATUS_IN_PROGRESS, model.JOB_STATUS_SUCCESS); result.Err != nil {
t.Fatal(result.Err)
} else {
if !result.Data.(bool) {
t.Fatal("should have succeeded")
}
}
if result := <-ss.Job().Get(job.Id); result.Err != nil {
t.Fatal(result.Err)
} else {
received := result.Data.(*model.Job)
if received.Status != model.JOB_STATUS_SUCCESS {
t.Fatal("should be success status")
}
if received.StartAt != startAtSet {
t.Fatal("startAt should not have changed")
}
if received.LastActivityAt <= lastUpdateAt {
t.Fatal("lastActivityAt wasn't updated")
}
lastUpdateAt = received.LastActivityAt
}
}
func testJobDelete(t *testing.T, ss store.Store) {
job := store.Must(ss.Job().Save(&model.Job{
Id: model.NewId(),
})).(*model.Job)
if result := <-ss.Job().Delete(job.Id); result.Err != nil {
t.Fatal(result.Err)
}
}

56
store/storetest/license_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,56 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestLicenseStore(t *testing.T, ss store.Store) {
t.Run("Save", func(t *testing.T) { testLicenseStoreSave(t, ss) })
t.Run("Get", func(t *testing.T) { testLicenseStoreGet(t, ss) })
}
func testLicenseStoreSave(t *testing.T, ss store.Store) {
l1 := model.LicenseRecord{}
l1.Id = model.NewId()
l1.Bytes = "junk"
if err := (<-ss.License().Save(&l1)).Err; err != nil {
t.Fatal("couldn't save license record", err)
}
if err := (<-ss.License().Save(&l1)).Err; err != nil {
t.Fatal("shouldn't fail on trying to save existing license record", err)
}
l1.Id = ""
if err := (<-ss.License().Save(&l1)).Err; err == nil {
t.Fatal("should fail on invalid license", err)
}
}
func testLicenseStoreGet(t *testing.T, ss store.Store) {
l1 := model.LicenseRecord{}
l1.Id = model.NewId()
l1.Bytes = "junk"
store.Must(ss.License().Save(&l1))
if r := <-ss.License().Get(l1.Id); r.Err != nil {
t.Fatal("couldn't get license", r.Err)
} else {
if r.Data.(*model.LicenseRecord).Bytes != l1.Bytes {
t.Fatal("license bytes didn't match")
}
}
if err := (<-ss.License().Get("missing")).Err; err == nil {
t.Fatal("should fail on get license", err)
}
}

435
store/storetest/oauth_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,435 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestOAuthStore(t *testing.T, ss store.Store) {
t.Run("SaveApp", func(t *testing.T) { testOAuthStoreSaveApp(t, ss) })
t.Run("GetApp", func(t *testing.T) { testOAuthStoreGetApp(t, ss) })
t.Run("UpdateApp", func(t *testing.T) { testOAuthStoreUpdateApp(t, ss) })
t.Run("SaveAccessData", func(t *testing.T) { testOAuthStoreSaveAccessData(t, ss) })
t.Run("OAuthUpdateAccessData", func(t *testing.T) { testOAuthUpdateAccessData(t, ss) })
t.Run("GetAccessData", func(t *testing.T) { testOAuthStoreGetAccessData(t, ss) })
t.Run("RemoveAccessData", func(t *testing.T) { testOAuthStoreRemoveAccessData(t, ss) })
t.Run("SaveAuthData", func(t *testing.T) { testOAuthStoreSaveAuthData(t, ss) })
t.Run("GetAuthData", func(t *testing.T) { testOAuthStoreGetAuthData(t, ss) })
t.Run("RemoveAuthData", func(t *testing.T) { testOAuthStoreRemoveAuthData(t, ss) })
t.Run("RemoveAuthDataByUser", func(t *testing.T) { testOAuthStoreRemoveAuthDataByUser(t, ss) })
t.Run("OAuthGetAuthorizedApps", func(t *testing.T) { testOAuthGetAuthorizedApps(t, ss) })
t.Run("OAuthGetAccessDataByUserForApp", func(t *testing.T) { testOAuthGetAccessDataByUserForApp(t, ss) })
t.Run("DeleteApp", func(t *testing.T) { testOAuthStoreDeleteApp(t, ss) })
}
func testOAuthStoreSaveApp(t *testing.T, ss store.Store) {
a1 := model.OAuthApp{}
a1.CreatorId = model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com"
// Try to save an app that already has an Id
a1.Id = model.NewId()
if err := (<-ss.OAuth().SaveApp(&a1)).Err; err == nil {
t.Fatal("Should have failed, cannot add an OAuth app cannot be save with an Id, it has to be updated")
}
// Try to save an Invalid App
a1.Id = ""
if err := (<-ss.OAuth().SaveApp(&a1)).Err; err == nil {
t.Fatal("Should have failed, app should be invalid cause it doesn' have a name set")
}
// Save the app
a1.Id = ""
a1.Name = "TestApp" + model.NewId()
if err := (<-ss.OAuth().SaveApp(&a1)).Err; err != nil {
t.Fatal(err)
}
}
func testOAuthStoreGetApp(t *testing.T, ss store.Store) {
a1 := model.OAuthApp{}
a1.CreatorId = model.NewId()
a1.Name = "TestApp" + model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com"
store.Must(ss.OAuth().SaveApp(&a1))
// Lets try to get and app that does not exists
if err := (<-ss.OAuth().GetApp("fake0123456789abcderfgret1")).Err; err == nil {
t.Fatal("Should have failed. App does not exists")
}
if err := (<-ss.OAuth().GetApp(a1.Id)).Err; err != nil {
t.Fatal(err)
}
// Lets try and get the app from a user that hasn't created any apps
if result := (<-ss.OAuth().GetAppByUser("fake0123456789abcderfgret1", 0, 1000)); result.Err == nil {
if len(result.Data.([]*model.OAuthApp)) > 0 {
t.Fatal("Should have failed. Fake user hasn't created any apps")
}
} else {
t.Fatal(result.Err)
}
if err := (<-ss.OAuth().GetAppByUser(a1.CreatorId, 0, 1000)).Err; err != nil {
t.Fatal(err)
}
if err := (<-ss.OAuth().GetApps(0, 1000)).Err; err != nil {
t.Fatal(err)
}
}
func testOAuthStoreUpdateApp(t *testing.T, ss store.Store) {
a1 := model.OAuthApp{}
a1.CreatorId = model.NewId()
a1.Name = "TestApp" + model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com"
store.Must(ss.OAuth().SaveApp(&a1))
// temporarily save the created app id
id := a1.Id
a1.CreateAt = 1
a1.ClientSecret = "pwd"
a1.CreatorId = "12345678901234567890123456"
// Lets update the app by removing the name
a1.Name = ""
if result := <-ss.OAuth().UpdateApp(&a1); result.Err == nil {
t.Fatal("Should have failed. App name is not set")
}
// Lets not find the app that we are trying to update
a1.Id = "fake0123456789abcderfgret1"
a1.Name = "NewName"
if result := <-ss.OAuth().UpdateApp(&a1); result.Err == nil {
t.Fatal("Should have failed. Not able to find the app")
}
a1.Id = id
if result := <-ss.OAuth().UpdateApp(&a1); result.Err != nil {
t.Fatal(result.Err)
} else {
ua1 := (result.Data.([2]*model.OAuthApp)[0])
if ua1.Name != "NewName" {
t.Fatal("name did not update")
}
if ua1.CreateAt == 1 {
t.Fatal("create at should not have updated")
}
if ua1.CreatorId == "12345678901234567890123456" {
t.Fatal("creator id should not have updated")
}
}
}
func testOAuthStoreSaveAccessData(t *testing.T, ss store.Store) {
a1 := model.AccessData{}
a1.ClientId = model.NewId()
a1.UserId = model.NewId()
// Lets try and save an incomplete access data
if err := (<-ss.OAuth().SaveAccessData(&a1)).Err; err == nil {
t.Fatal("Should have failed. Access data needs the token")
}
a1.Token = model.NewId()
a1.RefreshToken = model.NewId()
a1.RedirectUri = "http://example.com"
if err := (<-ss.OAuth().SaveAccessData(&a1)).Err; err != nil {
t.Fatal(err)
}
}
func testOAuthUpdateAccessData(t *testing.T, ss store.Store) {
a1 := model.AccessData{}
a1.ClientId = model.NewId()
a1.UserId = model.NewId()
a1.Token = model.NewId()
a1.RefreshToken = model.NewId()
a1.ExpiresAt = model.GetMillis()
a1.RedirectUri = "http://example.com"
store.Must(ss.OAuth().SaveAccessData(&a1))
//Try to update to invalid Refresh Token
refreshToken := a1.RefreshToken
a1.RefreshToken = model.NewId() + "123"
if err := (<-ss.OAuth().UpdateAccessData(&a1)).Err; err == nil {
t.Fatal("Should have failed with invalid token")
}
//Try to update to invalid RedirectUri
a1.RefreshToken = model.NewId()
a1.RedirectUri = ""
if err := (<-ss.OAuth().UpdateAccessData(&a1)).Err; err == nil {
t.Fatal("Should have failed with invalid Redirect URI")
}
// Should update fine
a1.RedirectUri = "http://example.com"
if result := <-ss.OAuth().UpdateAccessData(&a1); result.Err != nil {
t.Fatal(result.Err)
} else {
ra1 := result.Data.(*model.AccessData)
if ra1.RefreshToken == refreshToken {
t.Fatal("refresh tokens didn't match")
}
}
}
func testOAuthStoreGetAccessData(t *testing.T, ss store.Store) {
a1 := model.AccessData{}
a1.ClientId = model.NewId()
a1.UserId = model.NewId()
a1.Token = model.NewId()
a1.RefreshToken = model.NewId()
a1.ExpiresAt = model.GetMillis()
a1.RedirectUri = "http://example.com"
store.Must(ss.OAuth().SaveAccessData(&a1))
if err := (<-ss.OAuth().GetAccessData("invalidToken")).Err; err == nil {
t.Fatal("Should have failed. There is no data with an invalid token")
}
if result := <-ss.OAuth().GetAccessData(a1.Token); result.Err != nil {
t.Fatal(result.Err)
} else {
ra1 := result.Data.(*model.AccessData)
if a1.Token != ra1.Token {
t.Fatal("tokens didn't match")
}
}
if err := (<-ss.OAuth().GetPreviousAccessData(a1.UserId, a1.ClientId)).Err; err != nil {
t.Fatal(err)
}
if err := (<-ss.OAuth().GetPreviousAccessData("user", "junk")).Err; err != nil {
t.Fatal(err)
}
// Try to get the Access data using an invalid refresh token
if err := (<-ss.OAuth().GetAccessDataByRefreshToken(a1.Token)).Err; err == nil {
t.Fatal("Should have failed. There is no data with an invalid token")
}
// Get the Access Data using the refresh token
if result := <-ss.OAuth().GetAccessDataByRefreshToken(a1.RefreshToken); result.Err != nil {
t.Fatal(result.Err)
} else {
ra1 := result.Data.(*model.AccessData)
if a1.RefreshToken != ra1.RefreshToken {
t.Fatal("tokens didn't match")
}
}
}
func testOAuthStoreRemoveAccessData(t *testing.T, ss store.Store) {
a1 := model.AccessData{}
a1.ClientId = model.NewId()
a1.UserId = model.NewId()
a1.Token = model.NewId()
a1.RefreshToken = model.NewId()
a1.RedirectUri = "http://example.com"
store.Must(ss.OAuth().SaveAccessData(&a1))
if err := (<-ss.OAuth().RemoveAccessData(a1.Token)).Err; err != nil {
t.Fatal(err)
}
if result := (<-ss.OAuth().GetPreviousAccessData(a1.UserId, a1.ClientId)); result.Err != nil {
} else {
if result.Data != nil {
t.Fatal("did not delete access token")
}
}
}
func testOAuthStoreSaveAuthData(t *testing.T, ss store.Store) {
a1 := model.AuthData{}
a1.ClientId = model.NewId()
a1.UserId = model.NewId()
a1.Code = model.NewId()
a1.RedirectUri = "http://example.com"
if err := (<-ss.OAuth().SaveAuthData(&a1)).Err; err != nil {
t.Fatal(err)
}
}
func testOAuthStoreGetAuthData(t *testing.T, ss store.Store) {
a1 := model.AuthData{}
a1.ClientId = model.NewId()
a1.UserId = model.NewId()
a1.Code = model.NewId()
a1.RedirectUri = "http://example.com"
store.Must(ss.OAuth().SaveAuthData(&a1))
if err := (<-ss.OAuth().GetAuthData(a1.Code)).Err; err != nil {
t.Fatal(err)
}
}
func testOAuthStoreRemoveAuthData(t *testing.T, ss store.Store) {
a1 := model.AuthData{}
a1.ClientId = model.NewId()
a1.UserId = model.NewId()
a1.Code = model.NewId()
a1.RedirectUri = "http://example.com"
store.Must(ss.OAuth().SaveAuthData(&a1))
if err := (<-ss.OAuth().RemoveAuthData(a1.Code)).Err; err != nil {
t.Fatal(err)
}
if err := (<-ss.OAuth().GetAuthData(a1.Code)).Err; err == nil {
t.Fatal("should have errored - auth code removed")
}
}
func testOAuthStoreRemoveAuthDataByUser(t *testing.T, ss store.Store) {
a1 := model.AuthData{}
a1.ClientId = model.NewId()
a1.UserId = model.NewId()
a1.Code = model.NewId()
a1.RedirectUri = "http://example.com"
store.Must(ss.OAuth().SaveAuthData(&a1))
if err := (<-ss.OAuth().PermanentDeleteAuthDataByUser(a1.UserId)).Err; err != nil {
t.Fatal(err)
}
}
func testOAuthGetAuthorizedApps(t *testing.T, ss store.Store) {
a1 := model.OAuthApp{}
a1.CreatorId = model.NewId()
a1.Name = "TestApp" + model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com"
store.Must(ss.OAuth().SaveApp(&a1))
// Lets try and get an Authorized app for a user who hasn't authorized it
if result := <-ss.OAuth().GetAuthorizedApps("fake0123456789abcderfgret1", 0, 1000); result.Err == nil {
if len(result.Data.([]*model.OAuthApp)) > 0 {
t.Fatal("Should have failed. Fake user hasn't authorized the app")
}
} else {
t.Fatal(result.Err)
}
// allow the app
p := model.Preference{}
p.UserId = a1.CreatorId
p.Category = model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP
p.Name = a1.Id
p.Value = "true"
store.Must(ss.Preference().Save(&model.Preferences{p}))
if result := <-ss.OAuth().GetAuthorizedApps(a1.CreatorId, 0, 1000); result.Err != nil {
t.Fatal(result.Err)
} else {
apps := result.Data.([]*model.OAuthApp)
if len(apps) == 0 {
t.Fatal("It should have return apps")
}
}
}
func testOAuthGetAccessDataByUserForApp(t *testing.T, ss store.Store) {
a1 := model.OAuthApp{}
a1.CreatorId = model.NewId()
a1.Name = "TestApp" + model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com"
store.Must(ss.OAuth().SaveApp(&a1))
// allow the app
p := model.Preference{}
p.UserId = a1.CreatorId
p.Category = model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP
p.Name = a1.Id
p.Value = "true"
store.Must(ss.Preference().Save(&model.Preferences{p}))
if result := <-ss.OAuth().GetAuthorizedApps(a1.CreatorId, 0, 1000); result.Err != nil {
t.Fatal(result.Err)
} else {
apps := result.Data.([]*model.OAuthApp)
if len(apps) == 0 {
t.Fatal("It should have return apps")
}
}
// save the token
ad1 := model.AccessData{}
ad1.ClientId = a1.Id
ad1.UserId = a1.CreatorId
ad1.Token = model.NewId()
ad1.RefreshToken = model.NewId()
ad1.RedirectUri = "http://example.com"
if err := (<-ss.OAuth().SaveAccessData(&ad1)).Err; err != nil {
t.Fatal(err)
}
if result := <-ss.OAuth().GetAccessDataByUserForApp(a1.CreatorId, a1.Id); result.Err != nil {
t.Fatal(result.Err)
} else {
accessData := result.Data.([]*model.AccessData)
if len(accessData) == 0 {
t.Fatal("It should have return access data")
}
}
}
func testOAuthStoreDeleteApp(t *testing.T, ss store.Store) {
a1 := model.OAuthApp{}
a1.CreatorId = model.NewId()
a1.Name = "TestApp" + model.NewId()
a1.CallbackUrls = []string{"https://nowhere.com"}
a1.Homepage = "https://nowhere.com"
store.Must(ss.OAuth().SaveApp(&a1))
// delete a non-existent app
if err := (<-ss.OAuth().DeleteApp("fakeclientId")).Err; err != nil {
t.Fatal(err)
}
s1 := model.Session{}
s1.UserId = model.NewId()
s1.Token = model.NewId()
s1.IsOAuth = true
store.Must(ss.Session().Save(&s1))
ad1 := model.AccessData{}
ad1.ClientId = a1.Id
ad1.UserId = a1.CreatorId
ad1.Token = s1.Token
ad1.RefreshToken = model.NewId()
ad1.RedirectUri = "http://example.com"
store.Must(ss.OAuth().SaveAccessData(&ad1))
if err := (<-ss.OAuth().DeleteApp(a1.Id)).Err; err != nil {
t.Fatal(err)
}
if err := (<-ss.Session().Get(s1.Token)).Err; err == nil {
t.Fatal("should error - session should be deleted")
}
if err := (<-ss.OAuth().GetAccessData(s1.Token)).Err; err == nil {
t.Fatal("should error - access data should be deleted")
}
}

1684
store/storetest/post_store.go Обычный файл

Разница между файлами не показана из-за своего большого размера Загрузить разницу

447
store/storetest/preference_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,447 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestPreferenceStore(t *testing.T, ss store.Store) {
t.Run("PreferenceSave", func(t *testing.T) { testPreferenceSave(t, ss) })
t.Run("PreferenceGet", func(t *testing.T) { testPreferenceGet(t, ss) })
t.Run("PreferenceGetCategory", func(t *testing.T) { testPreferenceGetCategory(t, ss) })
t.Run("PreferenceGetAll", func(t *testing.T) { testPreferenceGetAll(t, ss) })
t.Run("PreferenceDeleteByUser", func(t *testing.T) { testPreferenceDeleteByUser(t, ss) })
t.Run("IsFeatureEnabled", func(t *testing.T) { testIsFeatureEnabled(t, ss) })
t.Run("PreferenceDelete", func(t *testing.T) { testPreferenceDelete(t, ss) })
t.Run("PreferenceDeleteCategory", func(t *testing.T) { testPreferenceDeleteCategory(t, ss) })
t.Run("PreferenceDeleteCategoryAndName", func(t *testing.T) { testPreferenceDeleteCategoryAndName(t, ss) })
t.Run("PreferenceCleanupFlagsBatch", func(t *testing.T) { testPreferenceCleanupFlagsBatch(t, ss) })
}
func testPreferenceSave(t *testing.T, ss store.Store) {
id := model.NewId()
preferences := model.Preferences{
{
UserId: id,
Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW,
Name: model.NewId(),
Value: "value1a",
},
{
UserId: id,
Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW,
Name: model.NewId(),
Value: "value1b",
},
}
if count := store.Must(ss.Preference().Save(&preferences)); count != 2 {
t.Fatal("got incorrect number of rows saved")
}
for _, preference := range preferences {
if data := store.Must(ss.Preference().Get(preference.UserId, preference.Category, preference.Name)).(model.Preference); preference != data {
t.Fatal("got incorrect preference after first Save")
}
}
preferences[0].Value = "value2a"
preferences[1].Value = "value2b"
if count := store.Must(ss.Preference().Save(&preferences)); count != 2 {
t.Fatal("got incorrect number of rows saved")
}
for _, preference := range preferences {
if data := store.Must(ss.Preference().Get(preference.UserId, preference.Category, preference.Name)).(model.Preference); preference != data {
t.Fatal("got incorrect preference after second Save")
}
}
}
func testPreferenceGet(t *testing.T, ss store.Store) {
userId := model.NewId()
category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW
name := model.NewId()
preferences := model.Preferences{
{
UserId: userId,
Category: category,
Name: name,
},
{
UserId: userId,
Category: category,
Name: model.NewId(),
},
{
UserId: userId,
Category: model.NewId(),
Name: name,
},
{
UserId: model.NewId(),
Category: category,
Name: name,
},
}
store.Must(ss.Preference().Save(&preferences))
if result := <-ss.Preference().Get(userId, category, name); result.Err != nil {
t.Fatal(result.Err)
} else if data := result.Data.(model.Preference); data != preferences[0] {
t.Fatal("got incorrect preference")
}
// make sure getting a missing preference fails
if result := <-ss.Preference().Get(model.NewId(), model.NewId(), model.NewId()); result.Err == nil {
t.Fatal("no error on getting a missing preference")
}
}
func testPreferenceGetCategory(t *testing.T, ss store.Store) {
userId := model.NewId()
category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW
name := model.NewId()
preferences := model.Preferences{
{
UserId: userId,
Category: category,
Name: name,
},
// same user/category, different name
{
UserId: userId,
Category: category,
Name: model.NewId(),
},
// same user/name, different category
{
UserId: userId,
Category: model.NewId(),
Name: name,
},
// same name/category, different user
{
UserId: model.NewId(),
Category: category,
Name: name,
},
}
store.Must(ss.Preference().Save(&preferences))
if result := <-ss.Preference().GetCategory(userId, category); result.Err != nil {
t.Fatal(result.Err)
} else if data := result.Data.(model.Preferences); len(data) != 2 {
t.Fatal("got the wrong number of preferences")
} else if !((data[0] == preferences[0] && data[1] == preferences[1]) || (data[0] == preferences[1] && data[1] == preferences[0])) {
t.Fatal("got incorrect preferences")
}
// make sure getting a missing preference category doesn't fail
if result := <-ss.Preference().GetCategory(model.NewId(), model.NewId()); result.Err != nil {
t.Fatal(result.Err)
} else if data := result.Data.(model.Preferences); len(data) != 0 {
t.Fatal("shouldn't have got any preferences")
}
}
func testPreferenceGetAll(t *testing.T, ss store.Store) {
userId := model.NewId()
category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW
name := model.NewId()
preferences := model.Preferences{
{
UserId: userId,
Category: category,
Name: name,
},
// same user/category, different name
{
UserId: userId,
Category: category,
Name: model.NewId(),
},
// same user/name, different category
{
UserId: userId,
Category: model.NewId(),
Name: name,
},
// same name/category, different user
{
UserId: model.NewId(),
Category: category,
Name: name,
},
}
store.Must(ss.Preference().Save(&preferences))
if result := <-ss.Preference().GetAll(userId); result.Err != nil {
t.Fatal(result.Err)
} else if data := result.Data.(model.Preferences); len(data) != 3 {
t.Fatal("got the wrong number of preferences")
} else {
for i := 0; i < 3; i++ {
if data[0] != preferences[i] && data[1] != preferences[i] && data[2] != preferences[i] {
t.Fatal("got incorrect preferences")
}
}
}
}
func testPreferenceDeleteByUser(t *testing.T, ss store.Store) {
userId := model.NewId()
category := model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW
name := model.NewId()
preferences := model.Preferences{
{
UserId: userId,
Category: category,
Name: name,
},
// same user/category, different name
{
UserId: userId,
Category: category,
Name: model.NewId(),
},
// same user/name, different category
{
UserId: userId,
Category: model.NewId(),
Name: name,
},
// same name/category, different user
{
UserId: model.NewId(),
Category: category,
Name: name,
},
}
store.Must(ss.Preference().Save(&preferences))
if result := <-ss.Preference().PermanentDeleteByUser(userId); result.Err != nil {
t.Fatal(result.Err)
}
}
func testIsFeatureEnabled(t *testing.T, ss store.Store) {
feature1 := "testFeat1"
feature2 := "testFeat2"
feature3 := "testFeat3"
userId := model.NewId()
category := model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS
features := model.Preferences{
{
UserId: userId,
Category: category,
Name: store.FEATURE_TOGGLE_PREFIX + feature1,
Value: "true",
},
{
UserId: userId,
Category: category,
Name: model.NewId(),
Value: "false",
},
{
UserId: userId,
Category: model.NewId(),
Name: store.FEATURE_TOGGLE_PREFIX + feature1,
Value: "false",
},
{
UserId: model.NewId(),
Category: category,
Name: store.FEATURE_TOGGLE_PREFIX + feature2,
Value: "false",
},
{
UserId: model.NewId(),
Category: category,
Name: store.FEATURE_TOGGLE_PREFIX + feature3,
Value: "foobar",
},
}
store.Must(ss.Preference().Save(&features))
if result := <-ss.Preference().IsFeatureEnabled(feature1, userId); result.Err != nil {
t.Fatal(result.Err)
} else if data := result.Data.(bool); data != true {
t.Fatalf("got incorrect setting for feature1, %v=%v", true, data)
}
if result := <-ss.Preference().IsFeatureEnabled(feature2, userId); result.Err != nil {
t.Fatal(result.Err)
} else if data := result.Data.(bool); data != false {
t.Fatalf("got incorrect setting for feature2, %v=%v", false, data)
}
// make sure we get false if something different than "true" or "false" has been saved to database
if result := <-ss.Preference().IsFeatureEnabled(feature3, userId); result.Err != nil {
t.Fatal(result.Err)
} else if data := result.Data.(bool); data != false {
t.Fatalf("got incorrect setting for feature3, %v=%v", false, data)
}
// make sure false is returned if a non-existent feature is queried
if result := <-ss.Preference().IsFeatureEnabled("someOtherFeature", userId); result.Err != nil {
t.Fatal(result.Err)
} else if data := result.Data.(bool); data != false {
t.Fatalf("got incorrect setting for non-existent feature 'someOtherFeature', %v=%v", false, data)
}
}
func testPreferenceDelete(t *testing.T, ss store.Store) {
preference := model.Preference{
UserId: model.NewId(),
Category: model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW,
Name: model.NewId(),
Value: "value1a",
}
store.Must(ss.Preference().Save(&model.Preferences{preference}))
if prefs := store.Must(ss.Preference().GetAll(preference.UserId)).(model.Preferences); len([]model.Preference(prefs)) != 1 {
t.Fatal("should've returned 1 preference")
}
if result := <-ss.Preference().Delete(preference.UserId, preference.Category, preference.Name); result.Err != nil {
t.Fatal(result.Err)
}
if prefs := store.Must(ss.Preference().GetAll(preference.UserId)).(model.Preferences); len([]model.Preference(prefs)) != 0 {
t.Fatal("should've returned no preferences")
}
}
func testPreferenceDeleteCategory(t *testing.T, ss store.Store) {
category := model.NewId()
userId := model.NewId()
preference1 := model.Preference{
UserId: userId,
Category: category,
Name: model.NewId(),
Value: "value1a",
}
preference2 := model.Preference{
UserId: userId,
Category: category,
Name: model.NewId(),
Value: "value1a",
}
store.Must(ss.Preference().Save(&model.Preferences{preference1, preference2}))
if prefs := store.Must(ss.Preference().GetAll(userId)).(model.Preferences); len([]model.Preference(prefs)) != 2 {
t.Fatal("should've returned 2 preferences")
}
if result := <-ss.Preference().DeleteCategory(userId, category); result.Err != nil {
t.Fatal(result.Err)
}
if prefs := store.Must(ss.Preference().GetAll(userId)).(model.Preferences); len([]model.Preference(prefs)) != 0 {
t.Fatal("should've returned no preferences")
}
}
func testPreferenceDeleteCategoryAndName(t *testing.T, ss store.Store) {
category := model.NewId()
name := model.NewId()
userId := model.NewId()
userId2 := model.NewId()
preference1 := model.Preference{
UserId: userId,
Category: category,
Name: name,
Value: "value1a",
}
preference2 := model.Preference{
UserId: userId2,
Category: category,
Name: name,
Value: "value1a",
}
store.Must(ss.Preference().Save(&model.Preferences{preference1, preference2}))
if prefs := store.Must(ss.Preference().GetAll(userId)).(model.Preferences); len([]model.Preference(prefs)) != 1 {
t.Fatal("should've returned 1 preference")
}
if prefs := store.Must(ss.Preference().GetAll(userId2)).(model.Preferences); len([]model.Preference(prefs)) != 1 {
t.Fatal("should've returned 1 preference")
}
if result := <-ss.Preference().DeleteCategoryAndName(category, name); result.Err != nil {
t.Fatal(result.Err)
}
if prefs := store.Must(ss.Preference().GetAll(userId)).(model.Preferences); len([]model.Preference(prefs)) != 0 {
t.Fatal("should've returned no preferences")
}
if prefs := store.Must(ss.Preference().GetAll(userId2)).(model.Preferences); len([]model.Preference(prefs)) != 0 {
t.Fatal("should've returned no preferences")
}
}
func testPreferenceCleanupFlagsBatch(t *testing.T, ss store.Store) {
category := model.PREFERENCE_CATEGORY_FLAGGED_POST
userId := model.NewId()
o1 := &model.Post{}
o1.ChannelId = model.NewId()
o1.UserId = userId
o1.Message = "zz" + model.NewId() + "AAAAAAAAAAA"
o1.CreateAt = 1000
o1 = (<-ss.Post().Save(o1)).Data.(*model.Post)
preference1 := model.Preference{
UserId: userId,
Category: category,
Name: o1.Id,
Value: "true",
}
preference2 := model.Preference{
UserId: userId,
Category: category,
Name: model.NewId(),
Value: "true",
}
store.Must(ss.Preference().Save(&model.Preferences{preference1, preference2}))
result := <-ss.Preference().CleanupFlagsBatch(10000)
assert.Nil(t, result.Err)
result = <-ss.Preference().Get(userId, category, preference1.Name)
assert.Nil(t, result.Err)
result = <-ss.Preference().Get(userId, category, preference2.Name)
assert.NotNil(t, result.Err)
}

350
store/storetest/reaction_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,350 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestReactionStore(t *testing.T, ss store.Store) {
t.Run("ReactionSave", func(t *testing.T) { testReactionSave(t, ss) })
t.Run("ReactionDelete", func(t *testing.T) { testReactionDelete(t, ss) })
t.Run("ReactionGetForPost", func(t *testing.T) { testReactionGetForPost(t, ss) })
t.Run("ReactionDeleteAllWithEmojiName", func(t *testing.T) { testReactionDeleteAllWithEmojiName(t, ss) })
t.Run("PermanentDeleteBatch", func(t *testing.T) { testReactionStorePermanentDeleteBatch(t, ss) })
}
func testReactionSave(t *testing.T, ss store.Store) {
post := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
firstUpdateAt := post.UpdateAt
reaction1 := &model.Reaction{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: model.NewId(),
}
if result := <-ss.Reaction().Save(reaction1); result.Err != nil {
t.Fatal(result.Err)
} else if saved := result.Data.(*model.Reaction); saved.UserId != reaction1.UserId ||
saved.PostId != reaction1.PostId || saved.EmojiName != reaction1.EmojiName {
t.Fatal("should've saved reaction and returned it")
}
var secondUpdateAt int64
if postList := store.Must(ss.Post().Get(reaction1.PostId)).(*model.PostList); !postList.Posts[post.Id].HasReactions {
t.Fatal("should've set HasReactions = true on post")
} else if postList.Posts[post.Id].UpdateAt == firstUpdateAt {
t.Fatal("should've marked post as updated when HasReactions changed")
} else {
secondUpdateAt = postList.Posts[post.Id].UpdateAt
}
if result := <-ss.Reaction().Save(reaction1); result.Err != nil {
t.Log(result.Err)
t.Fatal("should've allowed saving a duplicate reaction")
}
// different user
reaction2 := &model.Reaction{
UserId: model.NewId(),
PostId: reaction1.PostId,
EmojiName: reaction1.EmojiName,
}
if result := <-ss.Reaction().Save(reaction2); result.Err != nil {
t.Fatal(result.Err)
}
if postList := store.Must(ss.Post().Get(reaction2.PostId)).(*model.PostList); postList.Posts[post.Id].UpdateAt != secondUpdateAt {
t.Fatal("shouldn't mark as updated when HasReactions hasn't changed")
}
// different post
reaction3 := &model.Reaction{
UserId: reaction1.UserId,
PostId: model.NewId(),
EmojiName: reaction1.EmojiName,
}
if result := <-ss.Reaction().Save(reaction3); result.Err != nil {
t.Fatal(result.Err)
}
// different emoji
reaction4 := &model.Reaction{
UserId: reaction1.UserId,
PostId: reaction1.PostId,
EmojiName: model.NewId(),
}
if result := <-ss.Reaction().Save(reaction4); result.Err != nil {
t.Fatal(result.Err)
}
// invalid reaction
reaction5 := &model.Reaction{
UserId: reaction1.UserId,
PostId: reaction1.PostId,
}
if result := <-ss.Reaction().Save(reaction5); result.Err == nil {
t.Fatal("should've failed for invalid reaction")
}
}
func testReactionDelete(t *testing.T, ss store.Store) {
post := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
reaction := &model.Reaction{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: model.NewId(),
}
store.Must(ss.Reaction().Save(reaction))
firstUpdateAt := store.Must(ss.Post().Get(reaction.PostId)).(*model.PostList).Posts[post.Id].UpdateAt
if result := <-ss.Reaction().Delete(reaction); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.Reaction().GetForPost(post.Id, false); result.Err != nil {
t.Fatal(result.Err)
} else if len(result.Data.([]*model.Reaction)) != 0 {
t.Fatal("should've deleted reaction")
}
if postList := store.Must(ss.Post().Get(post.Id)).(*model.PostList); postList.Posts[post.Id].HasReactions {
t.Fatal("should've set HasReactions = false on post")
} else if postList.Posts[post.Id].UpdateAt == firstUpdateAt {
t.Fatal("shouldn't mark as updated when HasReactions has changed after deleting reactions")
}
}
func testReactionGetForPost(t *testing.T, ss store.Store) {
postId := model.NewId()
userId := model.NewId()
reactions := []*model.Reaction{
{
UserId: userId,
PostId: postId,
EmojiName: "smile",
},
{
UserId: model.NewId(),
PostId: postId,
EmojiName: "smile",
},
{
UserId: userId,
PostId: postId,
EmojiName: "sad",
},
{
UserId: userId,
PostId: model.NewId(),
EmojiName: "angry",
},
}
for _, reaction := range reactions {
store.Must(ss.Reaction().Save(reaction))
}
if result := <-ss.Reaction().GetForPost(postId, false); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.([]*model.Reaction); len(returned) != 3 {
t.Fatal("should've returned 3 reactions")
} else {
for _, reaction := range reactions {
found := false
for _, returnedReaction := range returned {
if returnedReaction.UserId == reaction.UserId && returnedReaction.PostId == reaction.PostId &&
returnedReaction.EmojiName == reaction.EmojiName {
found = true
break
}
}
if !found && reaction.PostId == postId {
t.Fatalf("should've returned reaction for post %v", reaction)
} else if found && reaction.PostId != postId {
t.Fatal("shouldn't have returned reaction for another post")
}
}
}
// Should return cached item
if result := <-ss.Reaction().GetForPost(postId, true); result.Err != nil {
t.Fatal(result.Err)
} else if returned := result.Data.([]*model.Reaction); len(returned) != 3 {
t.Fatal("should've returned 3 reactions")
} else {
for _, reaction := range reactions {
found := false
for _, returnedReaction := range returned {
if returnedReaction.UserId == reaction.UserId && returnedReaction.PostId == reaction.PostId &&
returnedReaction.EmojiName == reaction.EmojiName {
found = true
break
}
}
if !found && reaction.PostId == postId {
t.Fatalf("should've returned reaction for post %v", reaction)
} else if found && reaction.PostId != postId {
t.Fatal("shouldn't have returned reaction for another post")
}
}
}
}
func testReactionDeleteAllWithEmojiName(t *testing.T, ss store.Store) {
emojiToDelete := model.NewId()
post := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
post2 := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
post3 := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
userId := model.NewId()
reactions := []*model.Reaction{
{
UserId: userId,
PostId: post.Id,
EmojiName: emojiToDelete,
},
{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: emojiToDelete,
},
{
UserId: userId,
PostId: post.Id,
EmojiName: "sad",
},
{
UserId: userId,
PostId: post2.Id,
EmojiName: "angry",
},
{
UserId: userId,
PostId: post3.Id,
EmojiName: emojiToDelete,
},
}
for _, reaction := range reactions {
store.Must(ss.Reaction().Save(reaction))
}
if result := <-ss.Reaction().DeleteAllWithEmojiName(emojiToDelete); result.Err != nil {
t.Fatal(result.Err)
}
// check that the reactions were deleted
if returned := store.Must(ss.Reaction().GetForPost(post.Id, false)).([]*model.Reaction); len(returned) != 1 {
t.Fatal("should've only removed reactions with emoji name")
} else {
for _, reaction := range returned {
if reaction.EmojiName == "smile" {
t.Fatal("should've removed reaction with emoji name")
}
}
}
if returned := store.Must(ss.Reaction().GetForPost(post2.Id, false)).([]*model.Reaction); len(returned) != 1 {
t.Fatal("should've only removed reactions with emoji name")
}
if returned := store.Must(ss.Reaction().GetForPost(post3.Id, false)).([]*model.Reaction); len(returned) != 0 {
t.Fatal("should've only removed reactions with emoji name")
}
// check that the posts are updated
if postList := store.Must(ss.Post().Get(post.Id)).(*model.PostList); !postList.Posts[post.Id].HasReactions {
t.Fatal("post should still have reactions")
}
if postList := store.Must(ss.Post().Get(post2.Id)).(*model.PostList); !postList.Posts[post2.Id].HasReactions {
t.Fatal("post should still have reactions")
}
if postList := store.Must(ss.Post().Get(post3.Id)).(*model.PostList); postList.Posts[post3.Id].HasReactions {
t.Fatal("post shouldn't have reactions any more")
}
}
func testReactionStorePermanentDeleteBatch(t *testing.T, ss store.Store) {
post := store.Must(ss.Post().Save(&model.Post{
ChannelId: model.NewId(),
UserId: model.NewId(),
})).(*model.Post)
reactions := []*model.Reaction{
{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: "sad",
CreateAt: 1000,
},
{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: "sad",
CreateAt: 1500,
},
{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: "sad",
CreateAt: 2000,
},
{
UserId: model.NewId(),
PostId: post.Id,
EmojiName: "sad",
CreateAt: 2000,
},
}
// Need to hang on to a reaction to delete later in order to clear the cache, as "allowFromCache" isn't honoured any more.
var lastReaction *model.Reaction
for _, reaction := range reactions {
lastReaction = store.Must(ss.Reaction().Save(reaction)).(*model.Reaction)
}
if returned := store.Must(ss.Reaction().GetForPost(post.Id, false)).([]*model.Reaction); len(returned) != 4 {
t.Fatal("expected 4 reactions")
}
store.Must(ss.Reaction().PermanentDeleteBatch(1800, 1000))
// This is to force a clear of the cache.
store.Must(ss.Reaction().Delete(lastReaction))
if returned := store.Must(ss.Reaction().GetForPost(post.Id, false)).([]*model.Reaction); len(returned) != 1 {
t.Fatalf("expected 1 reaction. Got: %v", len(returned))
}
}

250
store/storetest/session_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,250 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestSessionStore(t *testing.T, ss store.Store) {
t.Run("Save", func(t *testing.T) { testSessionStoreSave(t, ss) })
t.Run("SessionGet", func(t *testing.T) { testSessionGet(t, ss) })
t.Run("SessionGetWithDeviceId", func(t *testing.T) { testSessionGetWithDeviceId(t, ss) })
t.Run("SessionRemove", func(t *testing.T) { testSessionRemove(t, ss) })
t.Run("SessionRemoveAll", func(t *testing.T) { testSessionRemoveAll(t, ss) })
t.Run("SessionRemoveByUser", func(t *testing.T) { testSessionRemoveByUser(t, ss) })
t.Run("SessionRemoveToken", func(t *testing.T) { testSessionRemoveToken(t, ss) })
t.Run("SessionUpdateDeviceId", func(t *testing.T) { testSessionUpdateDeviceId(t, ss) })
t.Run("SessionUpdateDeviceId2", func(t *testing.T) { testSessionUpdateDeviceId2(t, ss) })
t.Run("UpdateLastActivityAt", func(t *testing.T) { testSessionStoreUpdateLastActivityAt(t, ss) })
t.Run("SessionCount", func(t *testing.T) { testSessionCount(t, ss) })
}
func testSessionStoreSave(t *testing.T, ss store.Store) {
s1 := model.Session{}
s1.UserId = model.NewId()
if err := (<-ss.Session().Save(&s1)).Err; err != nil {
t.Fatal(err)
}
}
func testSessionGet(t *testing.T, ss store.Store) {
s1 := model.Session{}
s1.UserId = model.NewId()
store.Must(ss.Session().Save(&s1))
s2 := model.Session{}
s2.UserId = s1.UserId
store.Must(ss.Session().Save(&s2))
s3 := model.Session{}
s3.UserId = s1.UserId
s3.ExpiresAt = 1
store.Must(ss.Session().Save(&s3))
if rs1 := (<-ss.Session().Get(s1.Id)); rs1.Err != nil {
t.Fatal(rs1.Err)
} else {
if rs1.Data.(*model.Session).Id != s1.Id {
t.Fatal("should match")
}
}
if rs2 := (<-ss.Session().GetSessions(s1.UserId)); rs2.Err != nil {
t.Fatal(rs2.Err)
} else {
if len(rs2.Data.([]*model.Session)) != 2 {
t.Fatal("should match len")
}
}
}
func testSessionGetWithDeviceId(t *testing.T, ss store.Store) {
s1 := model.Session{}
s1.UserId = model.NewId()
s1.ExpiresAt = model.GetMillis() + 10000
store.Must(ss.Session().Save(&s1))
s2 := model.Session{}
s2.UserId = s1.UserId
s2.DeviceId = model.NewId()
s2.ExpiresAt = model.GetMillis() + 10000
store.Must(ss.Session().Save(&s2))
s3 := model.Session{}
s3.UserId = s1.UserId
s3.ExpiresAt = 1
s3.DeviceId = model.NewId()
store.Must(ss.Session().Save(&s3))
if rs1 := (<-ss.Session().GetSessionsWithActiveDeviceIds(s1.UserId)); rs1.Err != nil {
t.Fatal(rs1.Err)
} else {
if len(rs1.Data.([]*model.Session)) != 1 {
t.Fatal("should match len")
}
}
}
func testSessionRemove(t *testing.T, ss store.Store) {
s1 := model.Session{}
s1.UserId = model.NewId()
store.Must(ss.Session().Save(&s1))
if rs1 := (<-ss.Session().Get(s1.Id)); rs1.Err != nil {
t.Fatal(rs1.Err)
} else {
if rs1.Data.(*model.Session).Id != s1.Id {
t.Fatal("should match")
}
}
store.Must(ss.Session().Remove(s1.Id))
if rs2 := (<-ss.Session().Get(s1.Id)); rs2.Err == nil {
t.Fatal("should have been removed")
}
}
func testSessionRemoveAll(t *testing.T, ss store.Store) {
s1 := model.Session{}
s1.UserId = model.NewId()
store.Must(ss.Session().Save(&s1))
if rs1 := (<-ss.Session().Get(s1.Id)); rs1.Err != nil {
t.Fatal(rs1.Err)
} else {
if rs1.Data.(*model.Session).Id != s1.Id {
t.Fatal("should match")
}
}
store.Must(ss.Session().RemoveAllSessions())
if rs2 := (<-ss.Session().Get(s1.Id)); rs2.Err == nil {
t.Fatal("should have been removed")
}
}
func testSessionRemoveByUser(t *testing.T, ss store.Store) {
s1 := model.Session{}
s1.UserId = model.NewId()
store.Must(ss.Session().Save(&s1))
if rs1 := (<-ss.Session().Get(s1.Id)); rs1.Err != nil {
t.Fatal(rs1.Err)
} else {
if rs1.Data.(*model.Session).Id != s1.Id {
t.Fatal("should match")
}
}
store.Must(ss.Session().PermanentDeleteSessionsByUser(s1.UserId))
if rs2 := (<-ss.Session().Get(s1.Id)); rs2.Err == nil {
t.Fatal("should have been removed")
}
}
func testSessionRemoveToken(t *testing.T, ss store.Store) {
s1 := model.Session{}
s1.UserId = model.NewId()
store.Must(ss.Session().Save(&s1))
if rs1 := (<-ss.Session().Get(s1.Id)); rs1.Err != nil {
t.Fatal(rs1.Err)
} else {
if rs1.Data.(*model.Session).Id != s1.Id {
t.Fatal("should match")
}
}
store.Must(ss.Session().Remove(s1.Token))
if rs2 := (<-ss.Session().Get(s1.Id)); rs2.Err == nil {
t.Fatal("should have been removed")
}
if rs3 := (<-ss.Session().GetSessions(s1.UserId)); rs3.Err != nil {
t.Fatal(rs3.Err)
} else {
if len(rs3.Data.([]*model.Session)) != 0 {
t.Fatal("should match len")
}
}
}
func testSessionUpdateDeviceId(t *testing.T, ss store.Store) {
s1 := model.Session{}
s1.UserId = model.NewId()
store.Must(ss.Session().Save(&s1))
if rs1 := (<-ss.Session().UpdateDeviceId(s1.Id, model.PUSH_NOTIFY_APPLE+":1234567890", s1.ExpiresAt)); rs1.Err != nil {
t.Fatal(rs1.Err)
}
s2 := model.Session{}
s2.UserId = model.NewId()
store.Must(ss.Session().Save(&s2))
if rs2 := (<-ss.Session().UpdateDeviceId(s2.Id, model.PUSH_NOTIFY_APPLE+":1234567890", s1.ExpiresAt)); rs2.Err != nil {
t.Fatal(rs2.Err)
}
}
func testSessionUpdateDeviceId2(t *testing.T, ss store.Store) {
s1 := model.Session{}
s1.UserId = model.NewId()
store.Must(ss.Session().Save(&s1))
if rs1 := (<-ss.Session().UpdateDeviceId(s1.Id, model.PUSH_NOTIFY_APPLE_REACT_NATIVE+":1234567890", s1.ExpiresAt)); rs1.Err != nil {
t.Fatal(rs1.Err)
}
s2 := model.Session{}
s2.UserId = model.NewId()
store.Must(ss.Session().Save(&s2))
if rs2 := (<-ss.Session().UpdateDeviceId(s2.Id, model.PUSH_NOTIFY_APPLE_REACT_NATIVE+":1234567890", s1.ExpiresAt)); rs2.Err != nil {
t.Fatal(rs2.Err)
}
}
func testSessionStoreUpdateLastActivityAt(t *testing.T, ss store.Store) {
s1 := model.Session{}
s1.UserId = model.NewId()
store.Must(ss.Session().Save(&s1))
if err := (<-ss.Session().UpdateLastActivityAt(s1.Id, 1234567890)).Err; err != nil {
t.Fatal(err)
}
if r1 := <-ss.Session().Get(s1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.Session).LastActivityAt != 1234567890 {
t.Fatal("LastActivityAt not updated correctly")
}
}
}
func testSessionCount(t *testing.T, ss store.Store) {
s1 := model.Session{}
s1.UserId = model.NewId()
s1.ExpiresAt = model.GetMillis() + 100000
store.Must(ss.Session().Save(&s1))
if r1 := <-ss.Session().AnalyticsSessionCount(); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(int64) == 0 {
t.Fatal("should have at least 1 session")
}
}
}

106
store/storetest/status_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,106 @@
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestStatusStore(t *testing.T, ss store.Store) {
t.Run("", func(t *testing.T) { testStatusStore(t, ss) })
t.Run("ActiveUserCount", func(t *testing.T) { testActiveUserCount(t, ss) })
}
func testStatusStore(t *testing.T, ss store.Store) {
status := &model.Status{UserId: model.NewId(), Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""}
if err := (<-ss.Status().SaveOrUpdate(status)).Err; err != nil {
t.Fatal(err)
}
status.LastActivityAt = 10
if err := (<-ss.Status().SaveOrUpdate(status)).Err; err != nil {
t.Fatal(err)
}
if err := (<-ss.Status().Get(status.UserId)).Err; err != nil {
t.Fatal(err)
}
status2 := &model.Status{UserId: model.NewId(), Status: model.STATUS_AWAY, Manual: false, LastActivityAt: 0, ActiveChannel: ""}
if err := (<-ss.Status().SaveOrUpdate(status2)).Err; err != nil {
t.Fatal(err)
}
status3 := &model.Status{UserId: model.NewId(), Status: model.STATUS_OFFLINE, Manual: false, LastActivityAt: 0, ActiveChannel: ""}
if err := (<-ss.Status().SaveOrUpdate(status3)).Err; err != nil {
t.Fatal(err)
}
if result := <-ss.Status().GetOnlineAway(); result.Err != nil {
t.Fatal(result.Err)
} else {
statuses := result.Data.([]*model.Status)
for _, status := range statuses {
if status.Status == model.STATUS_OFFLINE {
t.Fatal("should not have returned offline statuses")
}
}
}
if result := <-ss.Status().GetOnline(); result.Err != nil {
t.Fatal(result.Err)
} else {
statuses := result.Data.([]*model.Status)
for _, status := range statuses {
if status.Status != model.STATUS_ONLINE {
t.Fatal("should not have returned offline statuses")
}
}
}
if result := <-ss.Status().GetByIds([]string{status.UserId, "junk"}); result.Err != nil {
t.Fatal(result.Err)
} else {
statuses := result.Data.([]*model.Status)
if len(statuses) != 1 {
t.Fatal("should only have 1 status")
}
}
if err := (<-ss.Status().ResetAll()).Err; err != nil {
t.Fatal(err)
}
if result := <-ss.Status().Get(status.UserId); result.Err != nil {
t.Fatal(result.Err)
} else {
status := result.Data.(*model.Status)
if status.Status != model.STATUS_OFFLINE {
t.Fatal("should be offline")
}
}
if result := <-ss.Status().UpdateLastActivityAt(status.UserId, 10); result.Err != nil {
t.Fatal(result.Err)
}
}
func testActiveUserCount(t *testing.T, ss store.Store) {
status := &model.Status{UserId: model.NewId(), Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""}
store.Must(ss.Status().SaveOrUpdate(status))
if result := <-ss.Status().GetTotalActiveUsersCount(); result.Err != nil {
t.Fatal(result.Err)
} else {
count := result.Data.(int64)
if count <= 0 {
t.Fatal()
}
}
}

58
store/storetest/system_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,58 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestSystemStore(t *testing.T, ss store.Store) {
t.Run("", func(t *testing.T) { testSystemStore(t, ss) })
t.Run("SaveOrUpdate", func(t *testing.T) { testSystemStoreSaveOrUpdate(t, ss) })
}
func testSystemStore(t *testing.T, ss store.Store) {
system := &model.System{Name: model.NewId(), Value: "value"}
store.Must(ss.System().Save(system))
result := <-ss.System().Get()
systems := result.Data.(model.StringMap)
if systems[system.Name] != system.Value {
t.Fatal()
}
system.Value = "value2"
store.Must(ss.System().Update(system))
result2 := <-ss.System().Get()
systems2 := result2.Data.(model.StringMap)
if systems2[system.Name] != system.Value {
t.Fatal()
}
result3 := <-ss.System().GetByName(system.Name)
rsystem := result3.Data.(*model.System)
if rsystem.Value != system.Value {
t.Fatal()
}
}
func testSystemStoreSaveOrUpdate(t *testing.T, ss store.Store) {
system := &model.System{Name: model.NewId(), Value: "value"}
if err := (<-ss.System().SaveOrUpdate(system)).Err; err != nil {
t.Fatal(err)
}
system.Value = "value2"
if r := <-ss.System().SaveOrUpdate(system); r.Err != nil {
t.Fatal(r.Err)
}
}

1010
store/storetest/team_store.go Обычный файл

Разница между файлами не показана из-за своего большого размера Загрузить разницу

89
store/storetest/user_access_token_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,89 @@
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestUserAccessTokenStore(t *testing.T, ss store.Store) {
t.Run("UserAccessTokenSaveGetDelete", func(t *testing.T) { testUserAccessTokenSaveGetDelete(t, ss) })
}
func testUserAccessTokenSaveGetDelete(t *testing.T, ss store.Store) {
uat := &model.UserAccessToken{
Token: model.NewId(),
UserId: model.NewId(),
Description: "testtoken",
}
s1 := model.Session{}
s1.UserId = uat.UserId
s1.Token = uat.Token
store.Must(ss.Session().Save(&s1))
if result := <-ss.UserAccessToken().Save(uat); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.UserAccessToken().Get(uat.Id); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.(*model.UserAccessToken); received.Token != uat.Token {
t.Fatal("received incorrect token after save")
}
if result := <-ss.UserAccessToken().GetByToken(uat.Token); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.(*model.UserAccessToken); received.Token != uat.Token {
t.Fatal("received incorrect token after save")
}
if result := <-ss.UserAccessToken().GetByToken("notarealtoken"); result.Err == nil {
t.Fatal("should have failed on bad token")
}
if result := <-ss.UserAccessToken().GetByUser(uat.UserId, 0, 100); result.Err != nil {
t.Fatal(result.Err)
} else if received := result.Data.([]*model.UserAccessToken); len(received) != 1 {
t.Fatal("received incorrect number of tokens after save")
}
if result := <-ss.UserAccessToken().Delete(uat.Id); result.Err != nil {
t.Fatal(result.Err)
}
if err := (<-ss.Session().Get(s1.Token)).Err; err == nil {
t.Fatal("should error - session should be deleted")
}
if err := (<-ss.UserAccessToken().GetByToken(s1.Token)).Err; err == nil {
t.Fatal("should error - access token should be deleted")
}
s2 := model.Session{}
s2.UserId = uat.UserId
s2.Token = uat.Token
store.Must(ss.Session().Save(&s2))
if result := <-ss.UserAccessToken().Save(uat); result.Err != nil {
t.Fatal(result.Err)
}
if result := <-ss.UserAccessToken().DeleteAllForUser(uat.UserId); result.Err != nil {
t.Fatal(result.Err)
}
if err := (<-ss.Session().Get(s2.Token)).Err; err == nil {
t.Fatal("should error - session should be deleted")
}
if err := (<-ss.UserAccessToken().GetByToken(s2.Token)).Err; err == nil {
t.Fatal("should error - access token should be deleted")
}
}

2074
store/storetest/user_store.go Обычный файл

Разница между файлами не показана из-за своего большого размера Загрузить разницу

507
store/storetest/webhook_store.go Обычный файл
Просмотреть файл

@@ -0,0 +1,507 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
package storetest
import (
"testing"
"time"
"net/http"
"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/store"
)
func TestWebhookStore(t *testing.T, ss store.Store) {
t.Run("SaveIncoming", func(t *testing.T) { testWebhookStoreSaveIncoming(t, ss) })
t.Run("UpdateIncoming", func(t *testing.T) { testWebhookStoreUpdateIncoming(t, ss) })
t.Run("GetIncoming", func(t *testing.T) { testWebhookStoreGetIncoming(t, ss) })
t.Run("GetIncomingList", func(t *testing.T) { testWebhookStoreGetIncomingList(t, ss) })
t.Run("GetIncomingByTeam", func(t *testing.T) { testWebhookStoreGetIncomingByTeam(t, ss) })
t.Run("DeleteIncoming", func(t *testing.T) { testWebhookStoreDeleteIncoming(t, ss) })
t.Run("DeleteIncomingByChannel", func(t *testing.T) { testWebhookStoreDeleteIncomingByChannel(t, ss) })
t.Run("DeleteIncomingByUser", func(t *testing.T) { testWebhookStoreDeleteIncomingByUser(t, ss) })
t.Run("SaveOutgoing", func(t *testing.T) { testWebhookStoreSaveOutgoing(t, ss) })
t.Run("GetOutgoing", func(t *testing.T) { testWebhookStoreGetOutgoing(t, ss) })
t.Run("GetOutgoingList", func(t *testing.T) { testWebhookStoreGetOutgoingList(t, ss) })
t.Run("GetOutgoingByChannel", func(t *testing.T) { testWebhookStoreGetOutgoingByChannel(t, ss) })
t.Run("GetOutgoingByTeam", func(t *testing.T) { testWebhookStoreGetOutgoingByTeam(t, ss) })
t.Run("DeleteOutgoing", func(t *testing.T) { testWebhookStoreDeleteOutgoing(t, ss) })
t.Run("DeleteOutgoingByChannel", func(t *testing.T) { testWebhookStoreDeleteOutgoingByChannel(t, ss) })
t.Run("DeleteOutgoingByUser", func(t *testing.T) { testWebhookStoreDeleteOutgoingByUser(t, ss) })
t.Run("UpdateOutgoing", func(t *testing.T) { testWebhookStoreUpdateOutgoing(t, ss) })
t.Run("CountIncoming", func(t *testing.T) { testWebhookStoreCountIncoming(t, ss) })
t.Run("CountOutgoing", func(t *testing.T) { testWebhookStoreCountOutgoing(t, ss) })
}
func testWebhookStoreSaveIncoming(t *testing.T, ss store.Store) {
o1 := buildIncomingWebhook()
if err := (<-ss.Webhook().SaveIncoming(o1)).Err; err != nil {
t.Fatal("couldn't save item", err)
}
if err := (<-ss.Webhook().SaveIncoming(o1)).Err; err == nil {
t.Fatal("shouldn't be able to update from save")
}
}
func testWebhookStoreUpdateIncoming(t *testing.T, ss store.Store) {
o1 := buildIncomingWebhook()
o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
previousUpdatedAt := o1.UpdateAt
o1.DisplayName = "TestHook"
time.Sleep(10 * time.Millisecond)
if result := (<-ss.Webhook().UpdateIncoming(o1)); result.Err != nil {
t.Fatal("updation of incoming hook failed", result.Err)
} else {
if result.Data.(*model.IncomingWebhook).UpdateAt == previousUpdatedAt {
t.Fatal("should have updated the UpdatedAt of the hook")
}
if result.Data.(*model.IncomingWebhook).DisplayName != "TestHook" {
t.Fatal("display name is not updated")
}
}
}
func testWebhookStoreGetIncoming(t *testing.T, ss store.Store) {
o1 := buildIncomingWebhook()
o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-ss.Webhook().GetIncoming(o1.Id, false); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if r1 := <-ss.Webhook().GetIncoming(o1.Id, true); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if err := (<-ss.Webhook().GetIncoming("123", false)).Err; err == nil {
t.Fatal("Missing id should have failed")
}
if err := (<-ss.Webhook().GetIncoming("123", true)).Err; err == nil {
t.Fatal("Missing id should have failed")
}
if err := (<-ss.Webhook().GetIncoming("123", true)).Err; err.StatusCode != http.StatusNotFound {
t.Fatal("Should have set the status as not found for missing id")
}
}
func testWebhookStoreGetIncomingList(t *testing.T, ss store.Store) {
o1 := &model.IncomingWebhook{}
o1.ChannelId = model.NewId()
o1.UserId = model.NewId()
o1.TeamId = model.NewId()
o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-ss.Webhook().GetIncomingList(0, 1000); r1.Err != nil {
t.Fatal(r1.Err)
} else {
found := false
hooks := r1.Data.([]*model.IncomingWebhook)
for _, hook := range hooks {
if hook.Id == o1.Id {
found = true
}
}
if !found {
t.Fatal("missing webhook")
}
}
if result := <-ss.Webhook().GetIncomingList(0, 1); result.Err != nil {
t.Fatal(result.Err)
} else {
if len(result.Data.([]*model.IncomingWebhook)) != 1 {
t.Fatal("only 1 should be returned")
}
}
}
func testWebhookStoreGetIncomingByTeam(t *testing.T, ss store.Store) {
o1 := buildIncomingWebhook()
o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-ss.Webhook().GetIncomingByTeam(o1.TeamId, 0, 100); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.([]*model.IncomingWebhook)[0].CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if result := <-ss.Webhook().GetIncomingByTeam("123", 0, 100); result.Err != nil {
t.Fatal(result.Err)
} else {
if len(result.Data.([]*model.IncomingWebhook)) != 0 {
t.Fatal("no webhooks should have returned")
}
}
}
func testWebhookStoreDeleteIncoming(t *testing.T, ss store.Store) {
o1 := buildIncomingWebhook()
o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-ss.Webhook().GetIncoming(o1.Id, true); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if r2 := <-ss.Webhook().DeleteIncoming(o1.Id, model.GetMillis()); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Webhook().GetIncoming(o1.Id, true)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func testWebhookStoreDeleteIncomingByChannel(t *testing.T, ss store.Store) {
o1 := buildIncomingWebhook()
o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-ss.Webhook().GetIncoming(o1.Id, true); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if r2 := <-ss.Webhook().PermanentDeleteIncomingByChannel(o1.ChannelId); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Webhook().GetIncoming(o1.Id, true)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func testWebhookStoreDeleteIncomingByUser(t *testing.T, ss store.Store) {
o1 := buildIncomingWebhook()
o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r1 := <-ss.Webhook().GetIncoming(o1.Id, true); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.IncomingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if r2 := <-ss.Webhook().PermanentDeleteIncomingByUser(o1.UserId); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Webhook().GetIncoming(o1.Id, true)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func buildIncomingWebhook() *model.IncomingWebhook {
o1 := &model.IncomingWebhook{}
o1.ChannelId = model.NewId()
o1.UserId = model.NewId()
o1.TeamId = model.NewId()
return o1
}
func testWebhookStoreSaveOutgoing(t *testing.T, ss store.Store) {
o1 := model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
if err := (<-ss.Webhook().SaveOutgoing(&o1)).Err; err != nil {
t.Fatal("couldn't save item", err)
}
if err := (<-ss.Webhook().SaveOutgoing(&o1)).Err; err == nil {
t.Fatal("shouldn't be able to update from save")
}
}
func testWebhookStoreGetOutgoing(t *testing.T, ss store.Store) {
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-ss.Webhook().GetOutgoing(o1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.OutgoingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if err := (<-ss.Webhook().GetOutgoing("123")).Err; err == nil {
t.Fatal("Missing id should have failed")
}
}
func testWebhookStoreGetOutgoingList(t *testing.T, ss store.Store) {
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
o2 := &model.OutgoingWebhook{}
o2.ChannelId = model.NewId()
o2.CreatorId = model.NewId()
o2.TeamId = model.NewId()
o2.CallbackURLs = []string{"http://nowhere.com/"}
o2 = (<-ss.Webhook().SaveOutgoing(o2)).Data.(*model.OutgoingWebhook)
if r1 := <-ss.Webhook().GetOutgoingList(0, 1000); r1.Err != nil {
t.Fatal(r1.Err)
} else {
hooks := r1.Data.([]*model.OutgoingWebhook)
found1 := false
found2 := false
for _, hook := range hooks {
if hook.CreateAt != o1.CreateAt {
found1 = true
}
if hook.CreateAt != o2.CreateAt {
found2 = true
}
}
if !found1 {
t.Fatal("missing hook1")
}
if !found2 {
t.Fatal("missing hook2")
}
}
if result := <-ss.Webhook().GetOutgoingList(0, 2); result.Err != nil {
t.Fatal(result.Err)
} else {
if len(result.Data.([]*model.OutgoingWebhook)) != 2 {
t.Fatal("wrong number of hooks returned")
}
}
}
func testWebhookStoreGetOutgoingByChannel(t *testing.T, ss store.Store) {
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-ss.Webhook().GetOutgoingByChannel(o1.ChannelId, 0, 100); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.([]*model.OutgoingWebhook)[0].CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if result := <-ss.Webhook().GetOutgoingByChannel("123", -1, -1); result.Err != nil {
t.Fatal(result.Err)
} else {
if len(result.Data.([]*model.OutgoingWebhook)) != 0 {
t.Fatal("no webhooks should have returned")
}
}
}
func testWebhookStoreGetOutgoingByTeam(t *testing.T, ss store.Store) {
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-ss.Webhook().GetOutgoingByTeam(o1.TeamId, 0, 100); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.([]*model.OutgoingWebhook)[0].CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if result := <-ss.Webhook().GetOutgoingByTeam("123", -1, -1); result.Err != nil {
t.Fatal(result.Err)
} else {
if len(result.Data.([]*model.OutgoingWebhook)) != 0 {
t.Fatal("no webhooks should have returned")
}
}
}
func testWebhookStoreDeleteOutgoing(t *testing.T, ss store.Store) {
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-ss.Webhook().GetOutgoing(o1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.OutgoingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if r2 := <-ss.Webhook().DeleteOutgoing(o1.Id, model.GetMillis()); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Webhook().GetOutgoing(o1.Id)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func testWebhookStoreDeleteOutgoingByChannel(t *testing.T, ss store.Store) {
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-ss.Webhook().GetOutgoing(o1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.OutgoingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if r2 := <-ss.Webhook().PermanentDeleteOutgoingByChannel(o1.ChannelId); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Webhook().GetOutgoing(o1.Id)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func testWebhookStoreDeleteOutgoingByUser(t *testing.T, ss store.Store) {
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r1 := <-ss.Webhook().GetOutgoing(o1.Id); r1.Err != nil {
t.Fatal(r1.Err)
} else {
if r1.Data.(*model.OutgoingWebhook).CreateAt != o1.CreateAt {
t.Fatal("invalid returned webhook")
}
}
if r2 := <-ss.Webhook().PermanentDeleteOutgoingByUser(o1.CreatorId); r2.Err != nil {
t.Fatal(r2.Err)
}
if r3 := (<-ss.Webhook().GetOutgoing(o1.Id)); r3.Err == nil {
t.Log(r3.Data)
t.Fatal("Missing id should have failed")
}
}
func testWebhookStoreUpdateOutgoing(t *testing.T, ss store.Store) {
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
o1.Token = model.NewId()
if r2 := <-ss.Webhook().UpdateOutgoing(o1); r2.Err != nil {
t.Fatal(r2.Err)
}
}
func testWebhookStoreCountIncoming(t *testing.T, ss store.Store) {
o1 := &model.IncomingWebhook{}
o1.ChannelId = model.NewId()
o1.UserId = model.NewId()
o1.TeamId = model.NewId()
o1 = (<-ss.Webhook().SaveIncoming(o1)).Data.(*model.IncomingWebhook)
if r := <-ss.Webhook().AnalyticsIncomingCount(""); r.Err != nil {
t.Fatal(r.Err)
} else {
if r.Data.(int64) == 0 {
t.Fatal("should have at least 1 incoming hook")
}
}
}
func testWebhookStoreCountOutgoing(t *testing.T, ss store.Store) {
o1 := &model.OutgoingWebhook{}
o1.ChannelId = model.NewId()
o1.CreatorId = model.NewId()
o1.TeamId = model.NewId()
o1.CallbackURLs = []string{"http://nowhere.com/"}
o1 = (<-ss.Webhook().SaveOutgoing(o1)).Data.(*model.OutgoingWebhook)
if r := <-ss.Webhook().AnalyticsOutgoingCount(""); r.Err != nil {
t.Fatal(r.Err)
} else {
if r.Data.(int64) == 0 {
t.Fatal("should have at least 1 outgoing hook")
}
}
}