outbound_commit_postgres_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package outbound
  2. import (
  3. "os"
  4. "strings"
  5. "testing"
  6. "gorm.io/gorm"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database"
  8. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  9. )
  10. func TestAddTrafficReturnsDeferredCommitFailure(t *testing.T) {
  11. if os.Getenv("XUI_DB_TYPE") != "postgres" || strings.TrimSpace(os.Getenv("XUI_DB_DSN")) == "" {
  12. t.Skip("set XUI_DB_TYPE=postgres and XUI_DB_DSN to run commit-failure injection")
  13. }
  14. if err := database.InitDB(""); err != nil {
  15. t.Fatalf("InitDB: %v", err)
  16. }
  17. t.Cleanup(func() { _ = database.CloseDB() })
  18. db := database.GetDB()
  19. const parent = "outbound_commit_parent"
  20. const child = "outbound_commit_child"
  21. _ = db.Exec("DROP TABLE IF EXISTS " + child).Error
  22. _ = db.Exec("DROP TABLE IF EXISTS " + parent).Error
  23. if err := db.Exec("CREATE TABLE " + parent + " (id bigint PRIMARY KEY)").Error; err != nil {
  24. t.Fatal(err)
  25. }
  26. if err := db.Exec("CREATE TABLE " + child + " (id bigint PRIMARY KEY, parent_id bigint REFERENCES " + parent + "(id) DEFERRABLE INITIALLY DEFERRED)").Error; err != nil {
  27. t.Fatal(err)
  28. }
  29. t.Cleanup(func() {
  30. _ = db.Exec("DROP TABLE IF EXISTS " + child).Error
  31. _ = db.Exec("DROP TABLE IF EXISTS " + parent).Error
  32. })
  33. const callback = "test:outbound-deferred-commit"
  34. if err := db.Callback().Create().After("gorm:create").Register(callback, func(tx *gorm.DB) {
  35. if tx.Statement == nil || tx.Statement.Table != "outbound_traffics" {
  36. return
  37. }
  38. if result := tx.Session(&gorm.Session{NewDB: true}).Exec("INSERT INTO " + child + " (id, parent_id) VALUES (1, 999999)"); result.Error != nil {
  39. tx.AddError(result.Error)
  40. }
  41. }); err != nil {
  42. t.Fatal(err)
  43. }
  44. t.Cleanup(func() { _ = db.Callback().Create().Remove(callback) })
  45. err, _ := (&OutboundService{}).AddTraffic([]*xray.Traffic{{Tag: "commit-test", IsOutbound: true, Up: 1}}, nil)
  46. if err == nil || !strings.Contains(strings.ToLower(err.Error()), "foreign key") {
  47. t.Fatalf("AddTraffic error = %v, want deferred foreign-key commit failure", err)
  48. }
  49. }