command_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package command
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "path/filepath"
  6. "testing"
  7. "github.com/stretchr/testify/assert"
  8. "github.com/tal-tech/go-zero/tools/goctl/config"
  9. "github.com/tal-tech/go-zero/tools/goctl/util"
  10. )
  11. var (
  12. 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"
  13. cfg = &config.Config{
  14. NamingFormat: "gozero",
  15. }
  16. )
  17. func TestFromDDl(t *testing.T) {
  18. err := fromDDl("./user.sql", t.TempDir(), cfg, true, false)
  19. assert.Equal(t, errNotMatched, err)
  20. // case dir is not exists
  21. unknownDir := filepath.Join(t.TempDir(), "test", "user.sql")
  22. err = fromDDl(unknownDir, t.TempDir(), cfg, true, false)
  23. assert.True(t, func() bool {
  24. switch err.(type) {
  25. case *os.PathError:
  26. return true
  27. default:
  28. return false
  29. }
  30. }())
  31. // case empty src
  32. err = fromDDl("", t.TempDir(), cfg, true, false)
  33. if err != nil {
  34. assert.Equal(t, "expected path or path globbing patterns, but nothing found", err.Error())
  35. }
  36. tempDir := filepath.Join(t.TempDir(), "test")
  37. err = util.MkdirIfNotExist(tempDir)
  38. if err != nil {
  39. return
  40. }
  41. user1Sql := filepath.Join(tempDir, "user1.sql")
  42. user2Sql := filepath.Join(tempDir, "user2.sql")
  43. err = ioutil.WriteFile(user1Sql, []byte(sql), os.ModePerm)
  44. if err != nil {
  45. return
  46. }
  47. err = ioutil.WriteFile(user2Sql, []byte(sql), os.ModePerm)
  48. if err != nil {
  49. return
  50. }
  51. _, err = os.Stat(user1Sql)
  52. assert.Nil(t, err)
  53. _, err = os.Stat(user2Sql)
  54. assert.Nil(t, err)
  55. err = fromDDl(filepath.Join(tempDir, "user*.sql"), tempDir, cfg, true, false)
  56. assert.Nil(t, err)
  57. _, err = os.Stat(filepath.Join(tempDir, "usermodel.go"))
  58. assert.Nil(t, err)
  59. }