command_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package command
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "path/filepath"
  6. "testing"
  7. "git.i2edu.net/i2/go-zero/tools/goctl/model/sql/gen"
  8. "git.i2edu.net/i2/go-zero/tools/goctl/config"
  9. "git.i2edu.net/i2/go-zero/tools/goctl/util"
  10. "github.com/stretchr/testify/assert"
  11. )
  12. var (
  13. sql = "-- 用户表 --\nCREATE TABLE `user` (\n `id` bigint(10) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户名称',\n `password` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户密码',\n `mobile` varchar(255) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '手机号',\n `gender` char(5) COLLATE utf8mb4_general_ci NOT NULL COMMENT '男|女|未公开',\n `nickname` varchar(255) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '用户昵称',\n `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,\n `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`),\n UNIQUE KEY `name_index` (`name`),\n UNIQUE KEY `mobile_index` (`mobile`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;\n\n"
  14. cfg = &config.Config{
  15. NamingFormat: "gozero",
  16. }
  17. )
  18. func TestFromDDl(t *testing.T) {
  19. err := gen.Clean()
  20. assert.Nil(t, err)
  21. err = fromDDl("./user.sql", t.TempDir(), cfg, true, false)
  22. assert.Equal(t, errNotMatched, err)
  23. // case dir is not exists
  24. unknownDir := filepath.Join(t.TempDir(), "test", "user.sql")
  25. err = fromDDl(unknownDir, t.TempDir(), cfg, true, false)
  26. assert.True(t, func() bool {
  27. switch err.(type) {
  28. case *os.PathError:
  29. return true
  30. default:
  31. return false
  32. }
  33. }())
  34. // case empty src
  35. err = fromDDl("", t.TempDir(), cfg, true, false)
  36. if err != nil {
  37. assert.Equal(t, "expected path or path globbing patterns, but nothing found", err.Error())
  38. }
  39. tempDir := filepath.Join(t.TempDir(), "test")
  40. err = util.MkdirIfNotExist(tempDir)
  41. if err != nil {
  42. return
  43. }
  44. user1Sql := filepath.Join(tempDir, "user1.sql")
  45. user2Sql := filepath.Join(tempDir, "user2.sql")
  46. err = ioutil.WriteFile(user1Sql, []byte(sql), os.ModePerm)
  47. if err != nil {
  48. return
  49. }
  50. err = ioutil.WriteFile(user2Sql, []byte(sql), os.ModePerm)
  51. if err != nil {
  52. return
  53. }
  54. _, err = os.Stat(user1Sql)
  55. assert.Nil(t, err)
  56. _, err = os.Stat(user2Sql)
  57. assert.Nil(t, err)
  58. err = fromDDl(filepath.Join(tempDir, "user*.sql"), tempDir, cfg, true, false)
  59. assert.Nil(t, err)
  60. _, err = os.Stat(filepath.Join(tempDir, "usermodel.go"))
  61. assert.Nil(t, err)
  62. }