You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_fixtures.go 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "fmt"
  7. "time"
  8. "gopkg.in/testfixtures.v2"
  9. )
  10. var fixtures *testfixtures.Context
  11. // InitFixtures initialize test fixtures for a test database
  12. func InitFixtures(helper testfixtures.Helper, dir string) (err error) {
  13. testfixtures.SkipDatabaseNameCheck(true)
  14. fixtures, err = testfixtures.NewFolder(x.DB().DB, helper, dir)
  15. return err
  16. }
  17. // LoadFixtures load fixtures for a test database
  18. func LoadFixtures() error {
  19. var err error
  20. // Database transaction conflicts could occur and result in ROLLBACK
  21. // As a simple workaround, we just retry 20 times.
  22. for i := 0; i < 20; i++ {
  23. err = fixtures.Load()
  24. if err == nil {
  25. break
  26. }
  27. time.Sleep(200 * time.Millisecond)
  28. }
  29. if err != nil {
  30. fmt.Printf("LoadFixtures failed after retries: %v\n", err)
  31. }
  32. // Now if we're running postgres we need to tell it to update the sequences
  33. if x.Dialect().DriverName() == "postgres" {
  34. results, err := x.QueryString(`SELECT 'SELECT SETVAL(' ||
  35. quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) ||
  36. ', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' ||
  37. quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';'
  38. FROM pg_class AS S,
  39. pg_depend AS D,
  40. pg_class AS T,
  41. pg_attribute AS C,
  42. pg_tables AS PGT
  43. WHERE S.relkind = 'S'
  44. AND S.oid = D.objid
  45. AND D.refobjid = T.oid
  46. AND D.refobjid = C.attrelid
  47. AND D.refobjsubid = C.attnum
  48. AND T.relname = PGT.tablename
  49. ORDER BY S.relname;`)
  50. if err != nil {
  51. fmt.Printf("Failed to generate sequence update: %v\n", err)
  52. return err
  53. }
  54. for _, r := range results {
  55. for _, value := range r {
  56. _, err = x.Exec(value)
  57. if err != nil {
  58. fmt.Printf("Failed to update sequence: %s Error: %v\n", value, err)
  59. return err
  60. }
  61. }
  62. }
  63. }
  64. return err
  65. }