Esempio n. 1
0
// sub-select not implemented in exec yet
func testSubselect(t *testing.T) {
	sqlText := `
		select 
	        user_id, email
	    FROM users
	    WHERE user_id in 
	        (select user_id from orders)
    `
	job, err := BuildSqlJob(rtConf, "mockcsv", sqlText)
	assert.Tf(t, err == nil, "no error %v", err)

	//writeCtx := NewContextSimple()
	msgs := make([]datasource.Message, 0)
	go func() {
		outChan := job.DrainChan()
		for msg := range outChan {
			u.Infof("msg: %v", msg)
			msgs = append(msgs, msg)
		}
	}()
	err = job.Run()
	time.Sleep(time.Millisecond * 30)
	assert.Tf(t, err == nil, "no error %v", err)
	assert.Tf(t, len(msgs) == 1, "should have filtered out 2 messages")

}
Esempio n. 2
0
// Test an actual file patch on the munged file scenario from TestMatchMunge.
// Resulting patched file should be identical to the source file.
func TestPatch(t *testing.T) {
	srcPath := "../../testroot/My Music/0 10k 30.mp4"
	dstPath := filepath.Join(os.TempDir(), "foo.mp4")

	os.Remove(dstPath)

	origDstF, err := os.Open("../../testroot/My Music/0 10k 30 munged.mp4")
	assert.Tf(t, err == nil, "%v", err)

	dstF, err := os.Create(dstPath)
	assert.Tf(t, err == nil, "%v", err)

	_, err = io.Copy(dstF, origDstF)
	assert.Tf(t, err == nil, "%v", err)

	origDstF.Close()
	dstF.Close()

	err = PatchFile(srcPath, dstPath)
	if err != nil {
		fmt.Print(err.Error())
	}
	assert.T(t, err == nil)

	srcFile, err := fs.IndexFile(srcPath)
	assert.T(t, err == nil)

	dstFile, err := fs.IndexFile(dstPath)
	assert.Tf(t, err == nil, "%v", err)

	assert.Equal(t, srcFile.Strong(), dstFile.Strong())
}
Esempio n. 3
0
// Test the matcher on a case where the source file has the same 
// prefix as destination, but has been appended to.
func TestMatchAppend(t *testing.T) {
	tg := treegen.New()
	treeSpec := tg.F("bar", tg.B(42, 65537), tg.B(43, 65537))

	srcpath := treegen.TestTree(t, treeSpec)
	defer os.RemoveAll(srcpath)

	// Try indexing root dir as a file
	srcFile, err := fs.IndexFile(srcpath)
	assert.Tf(t, err != nil, "%v", err)

	// Ok, for real this time
	srcFile, err = fs.IndexFile(filepath.Join(srcpath, "bar"))
	assert.Tf(t, err == nil, "%v", err)
	assert.Equal(t, 17, len(srcFile.Blocks))

	tg = treegen.New()
	treeSpec = tg.F("bar", tg.B(42, 65537))

	dstpath := treegen.TestTree(t, treeSpec)
	defer os.RemoveAll(dstpath)
	dstFile, err := fs.IndexFile(filepath.Join(dstpath, "bar"))
	assert.Equal(t, 9, len(dstFile.Blocks))

	match, err := MatchFile(srcFile, filepath.Join(dstpath, "bar"))
	assert.T(t, err == nil, "%v", err)

	assert.Equal(t, 8, len(match.BlockMatches))

	notMatched := match.NotMatched()
	assert.Equal(t, 1, len(notMatched))
	assert.Equal(t, int64(65536), notMatched[0].From)
	assert.Equal(t, int64(65537+65537), notMatched[0].To)
}
Esempio n. 4
0
func TestSqlShow(t *testing.T) {
	/*
		SHOW [FULL] TABLES [{FROM | IN} db_name]
		[LIKE 'pattern' | WHERE expr]
	*/
	sql := `show tables`
	req, err := ParseSql(sql)
	assert.Tf(t, err == nil && req != nil, "Must parse: %s  \n\t%v", sql, err)
	cmd, ok := req.(*SqlShow)
	assert.Tf(t, ok, "is SqlShow: %T", req)
	assert.Tf(t, cmd.Identity == "tables", "has SHOW kw: %#v", cmd)
	/*
		assert.Tf(t, len(cmd.Columns) == 1 && cmd.Columns[0].Name == "autocommit", "has autocommit: %#v", cmd.Columns)

		sql = `SET @@local.sort_buffer_size=10000;`
		req, err = ParseSql(sql)
		assert.Tf(t, err == nil && req != nil, "Must parse: %s  \n\t%v", sql, err)
		cmd, ok = req.(*SqlCommand)
		assert.Tf(t, ok, "is SqlCommand: %T", req)
		assert.Tf(t, cmd.Keyword() == lex.TokenSet, "has SET kw: %#v", cmd)
		assert.Tf(t, len(cmd.Columns) == 1 && cmd.Columns[0].Name == "@@local.sort_buffer_size", "has autocommit: %#v", cmd.Columns)

		sql = "USE `myschema`;"
		req, err = ParseSql(sql)
		assert.Tf(t, err == nil && req != nil, "Must parse: %s  \n\t%v", sql, err)
		cmd, ok = req.(*SqlCommand)
		assert.Tf(t, ok, "is SqlCommand: %T", req)
		assert.Tf(t, cmd.Keyword() == lex.TokenUse, "has USE kw: %#v", cmd)
		assert.Tf(t, len(cmd.Columns) == 1 && cmd.Columns[0].Name == "myschema", "has myschema: %#v", cmd.Columns[0])
	*/
}
Esempio n. 5
0
func TestWithJson(t *testing.T) {
	// This is obviously not exactly sql standard
	// but is nice for proxy's
	sql := `
		SELECT id, name FROM user
		WITH {
			"key":"value2"
			,"keyint":45,
			"keyfloat":55.5, 
			"keybool": true,
			"keyarraymixed":["a",2,"b"],
			"keyarrayobj":[
				{"hello":"value","age":55},
				{"hello":"value","age":55}
			],
			"keyobj":{"hello":"value","age":55},
			"keyobjnested":{
				"hello":"value",
				"array":[
					"a",
					2,
					"b"
				]
			}
		}
		`
	req, err := ParseSql(sql)
	assert.Tf(t, err == nil && req != nil, "Must parse: %s  \n\t%v", sql, err)
	sel, ok := req.(*SqlSelect)
	assert.Tf(t, ok, "is SqlSelect: %T", req)
	assert.Tf(t, len(sel.From) == 1 && sel.From[0].Name == "user", "has 1 from: %v", sel.From)
	assert.Tf(t, len(sel.With) == 8, "has with: %v", sel.With)
	assert.Tf(t, len(sel.With.Helper("keyobj")) == 2, "has 2obj keys: %v", sel.With.Helper("keyobj"))
	u.Infof("sel.With:  \n%s", sel.With.PrettyJson())
}
Esempio n. 6
0
func TestSqlDelete(t *testing.T) {

	db := datasource.NewContextSimple()
	user1 := map[string]value.Value{
		"user_id":    value.NewIntValue(5),
		"item_count": value.NewStringValue("5"),
		"bval":       value.NewBoolValue(true),
		"bvalf":      value.NewBoolValue(false),
		"reg_date":   value.NewStringValue("2014/11/01"),
		"name":       value.NewStringValue("bob")}
	db.Insert(user1)
	user2 := map[string]value.Value{
		"user_id":    value.NewIntValue(6),
		"item_count": value.NewStringValue("5"),
		"reg_date":   value.NewStringValue("2012/11/01"),
		"name":       value.NewStringValue("allison")}
	db.Insert(user2)
	assert.Tf(t, len(db.Rows) == 2, "has 2 users")
	verifySqlDelete(t, `
		DELETE FROM mytable
		WHERE yy(reg_date) == 14
		`, db)

	assert.Tf(t, len(db.Rows) == 1, "must have 1 rows: %v  %v", len(db.Rows), db.Rows)
	assert.Tf(t, db.Rows[0]["name"].ToString() == "allison", "%v", db.Rows)
}
Esempio n. 7
0
// 18.9.9. Find node by exact match
func TestFindNodeByExactMatch(t *testing.T) {
	db := connectTest(t)
	defer cleanup(t, db)
	// Create
	idxName := rndStr(t)
	key0 := rndStr(t)
	key1 := rndStr(t)
	value0 := rndStr(t)
	value1 := rndStr(t)
	idx0, _ := db.CreateLegacyNodeIndex(idxName, "", "")
	defer idx0.Delete()
	n0, _ := db.CreateNode(Props{})
	n1, _ := db.CreateNode(Props{})
	n2, _ := db.CreateNode(Props{})
	// These two will be located by Find() below
	idx0.Add(n0, key0, value0)
	idx0.Add(n1, key0, value0)
	// These two will NOT be located by Find() below
	idx0.Add(n2, key1, value0)
	idx0.Add(n2, key0, value1)
	//
	nodes, err := idx0.Find(key0, value0)
	if err != nil {
		t.Error(err)
	}
	// This query should have returned a map containing just two nodes, n1 and n0.
	assert.Equal(t, len(nodes), 2)
	_, present := nodes[n0.Id()]
	assert.Tf(t, present, "Find() failed to return node with id "+strconv.Itoa(n0.Id()))
	_, present = nodes[n1.Id()]
	assert.Tf(t, present, "Find() failed to return node with id "+strconv.Itoa(n1.Id()))
}
Esempio n. 8
0
func TestExecHaving(t *testing.T) {
	sqlText := `
		select 
	        user_id, count(user_id) AS order_ct
	    FROM orders
	    GROUP BY user_id
	    HAVING order_ct > 1
	`
	ctx := td.TestContext(sqlText)
	job, err := exec.BuildSqlJob(ctx)
	assert.Tf(t, err == nil, "no error %v", err)

	msgs := make([]schema.Message, 0)
	resultWriter := exec.NewResultBuffer(ctx, &msgs)
	job.RootTask.Add(resultWriter)

	err = job.Setup()
	assert.T(t, err == nil)
	err = job.Run()
	time.Sleep(time.Millisecond * 10)
	assert.Tf(t, err == nil, "no error %v", err)
	assert.Tf(t, len(msgs) == 1, "should have filtered HAVING orders into 1 users %v", len(msgs))
	u.Debugf("msg: %#v", msgs[0])
	row := msgs[0].(*datasource.SqlDriverMessageMap).Values()
	u.Debugf("row: %#v", row)
	assert.Tf(t, len(row) == 2, "expects 2 cols but got %v", len(row))
	assert.T(t, row[0] == "9Ip1aKbeZe2njCDM")
	// I really don't like this float behavior?
	assert.Tf(t, int(row[1].(int64)) == 2, "expected 2 orders for %v", row)
}
Esempio n. 9
0
func TestThrottleer(t *testing.T) {
	th := NewThrottler(10, 10*time.Second)
	for i := 0; i < 10; i++ {
		thb, tc := th.Throttle()
		assert.Tf(t, thb == false, "Should not throttle %v", i)
		assert.Tf(t, tc < 10, "Throttle count should remain below 10 %v", tc)
		time.Sleep(time.Millisecond * 10)
	}

	throttled := 0
	th = NewThrottler(10, 1*time.Second)
	// We are going to loop 20 times, first 10 should make it, next 10 throttled
	for i := 0; i < 20; i++ {
		LogThrottleKey(WARN, 10, "throttle", "hello %v", i)
		thb, tc := th.Throttle()

		if thb {
			throttled += 1
			assert.Tf(t, int(tc) == i-9, "Throttle count should rise %v, i: %d", tc, i)
		}
	}
	assert.Tf(t, throttled == 10, "Should throttle 10 of 20 requests: %v", throttled)

	// Now sleep for 1 second so that we should
	// no longer be throttled
	time.Sleep(time.Second * 2)
	thb, _ := th.Throttle()
	assert.Tf(t, thb == false, "We should not have been throttled")
}
Esempio n. 10
0
// 18.5.12. Get typed relationships
func TestGetTypedRelationships(t *testing.T) {
	db := connectTest(t)
	defer cleanup(t, db)
	// Create
	relType0 := rndStr(t)
	relType1 := rndStr(t)
	n0, _ := db.CreateNode(Props{})
	n1, _ := db.CreateNode(Props{})
	r0, _ := n0.Relate(relType0, n1.Id(), Props{})
	r1, _ := n0.Relate(relType1, n1.Id(), Props{})
	// Check one type of relationship
	rels, err := n0.Relationships(relType0)
	if err != nil {
		t.Error(err)
	}
	assert.Equalf(t, len(rels), 1, "Wrong number of relationships")
	_, present := rels.Map()[r0.Id()]
	assert.Tf(t, present, "Missing expected relationship")
	// Check two types of relationship together
	rels, err = n0.Relationships(relType0, relType1)
	if err != nil {
		t.Error(err)
	}
	assert.Equalf(t, len(rels), 2, "Wrong number of relationships")
	for _, r := range []*Relationship{r0, r1} {
		_, present := rels.Map()[r.Id()]
		assert.Tf(t, present, "Missing expected relationship")
	}
}
Esempio n. 11
0
func ExecSpec(t *testing.T, q *QuerySpec) {
	ctx := td.TestContext(q.sql)
	job, err := exec.BuildSqlJob(ctx)
	if !q.haserr {
		assert.Tf(t, err == nil, "expected no error but got %v for %s", err, q.sql)
	} else {
		assert.Tf(t, err != nil, "expected error but got %v for %s", err, q.sql)
		return
	}

	msgs := make([]schema.Message, 0)
	resultWriter := exec.NewResultBuffer(ctx, &msgs)
	job.RootTask.Add(resultWriter)

	err = job.Setup()
	if !q.haserr {

	}
	assert.T(t, err == nil)
	err = job.Run()
	//time.Sleep(time.Millisecond * 1)
	assert.Tf(t, err == nil, "got err=%v for sql=%s", err, q.sql)
	assert.Tf(t, len(msgs) == q.rowct, "expected %d rows but got %v for %s", q.rowct, len(msgs), q.sql)
	for rowi, msg := range msgs {
		row := msg.(*datasource.SqlDriverMessageMap).Values()
		expect := q.expect[rowi]
		//u.Debugf("msg?  %#v", msg)
		assert.Tf(t, len(row) == len(expect), "expects %d cols but got %v for sql=%s", len(expect), len(row), q.sql)
		for i, v := range row {
			assert.Equalf(t, expect[i], v, "Comparing values, col:%d expected %v:%T got %v:%T for sql=%s",
				i, expect[i], expect[i], v, v, q.sql)
		}
	}
}
Esempio n. 12
0
func DoTestPatchFileAppend(t *testing.T, mkrepo repoMaker) {
	tg := treegen.New()
	treeSpec := tg.D("foo", tg.F("bar", tg.B(42, 65537), tg.B(43, 65537)))

	srcpath := treegen.TestTree(t, treeSpec)
	defer os.RemoveAll(srcpath)
	srcRepo := mkrepo(t)
	defer srcRepo.Close()
	srcStore, err := fs.NewLocalStore(srcpath, srcRepo)
	assert.T(t, err == nil)

	tg = treegen.New()
	treeSpec = tg.D("foo", tg.F("bar", tg.B(42, 65537)))

	dstpath := treegen.TestTree(t, treeSpec)
	defer os.RemoveAll(dstpath)
	dstRepo := mkrepo(t)
	defer dstRepo.Close()
	dstStore, err := fs.NewLocalStore(dstpath, dstRepo)
	assert.T(t, err == nil)

	patchPlan := NewPatchPlan(srcStore, dstStore)
	//	printPlan(patchPlan)

	complete := false
	for i, cmd := range patchPlan.Cmds {
		switch {
		case i == 0:
			localTemp, isTemp := cmd.(*LocalTemp)
			assert.T(t, isTemp)
			assert.Equal(t, filepath.Join(dstpath, "foo", "bar"), localTemp.Path.Resolve())
		case i >= 1 && i <= 8:
			ltc, isLtc := cmd.(*LocalTempCopy)
			assert.Tf(t, isLtc, "cmd %d", i)
			assert.Equal(t, ltc.LocalOffset, ltc.TempOffset)
			assert.Equal(t, int64(fs.BLOCKSIZE), ltc.Length)
			assert.Equal(t, int64(0), ltc.LocalOffset%int64(fs.BLOCKSIZE))
		case i == 9:
			stc, isStc := cmd.(*SrcTempCopy)
			assert.T(t, isStc)
			assert.Equal(t, int64(65538), stc.Length)
		case i == 10:
			_, isRwt := cmd.(*ReplaceWithTemp)
			assert.T(t, isRwt)
			complete = true
		case i > 10:
			t.Fatalf("too many commands")
		}
	}
	assert.T(t, complete, "missing expected number of commands")

	failedCmd, err := patchPlan.Exec()
	assert.Tf(t, failedCmd == nil && err == nil, "%v: %v", failedCmd, err)

	srcRoot, errors := fs.IndexDir(srcpath, fs.NewMemRepo())
	assert.Equalf(t, 0, len(errors), "%v", errors)
	dstRoot, errors := fs.IndexDir(dstpath, fs.NewMemRepo())
	assert.Equalf(t, 0, len(errors), "%v", errors)
	assert.Equal(t, srcRoot.Info().Strong, dstRoot.Info().Strong)
}
Esempio n. 13
0
func TestMainWriter_Write(t *testing.T) {
	var out bytes.Buffer
	b := mainWriter{
		&task.TaskSet{
			ImportPath: "github.com/jingweno/gotask/examples",
			Tasks: []task.Task{
				{
					Name:        "HelloWorld",
					ActionName:  "TaskHelloWorld",
					Usage:       "Say Hello world",
					Description: "Print out Hello World",
					Flags: []task.Flag{
						task.NewBoolFlag("v, verbose", "Run in verbose mode"),
					},
				},
			},
		},
	}
	b.Write(&out)

	assert.Tf(t, strings.Contains(out.String(), `_task "github.com/jingweno/gotask/examples"`), "%v", out.String())
	assert.Tf(t, strings.Contains(out.String(), `Name: "HelloWorld"`), "%v", out.String())
	assert.Tf(t, strings.Contains(out.String(), `Usage: "Say Hello world"`), "%v", out.String())
	assert.Tf(t, strings.Contains(out.String(), `Description: "Print out Hello World`), "%v", out.String())
	assert.Tf(t, strings.Contains(out.String(), `task.NewBoolFlag("v, verbose", "Run in verbose mode")`), "%v", out.String())
}
Esempio n. 14
0
func TestBuiltins(t *testing.T) {
	for _, biTest := range builtinTests {
		node, err := ParseExpression(biTest.expr)
		assert.Tf(t, err == nil, "nil err: %v", err)
		assert.Tf(t, node != nil, "has node: %v", node)
	}
}
Esempio n. 15
0
func TestResponseError_Error_401(t *testing.T) {
	setup()
	defer tearDown()

	mux.HandleFunc("/error", func(w http.ResponseWriter, r *http.Request) {
		head := w.Header()
		head.Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusUnauthorized)
		respondWith(w, `{"message":"Unauthorized"}`)
	})

	req, _ := client.NewRequest("error")
	_, err := req.Get(nil)
	assert.Tf(t, strings.Contains(err.Error(), "401 - Unauthorized"), "%s", err.Error())

	e := err.(*ResponseError)
	assert.Equal(t, ErrorUnauthorized, e.Type)

	mux.HandleFunc("/error_2fa", func(w http.ResponseWriter, r *http.Request) {
		head := w.Header()
		head.Set("Content-Type", "application/json")
		head.Set("X-GitHub-OTP", "required; app")
		w.WriteHeader(http.StatusUnauthorized)
		respondWith(w, `{"message":"Unauthorized"}`)
	})

	req, _ = client.NewRequest("error_2fa")
	_, err = req.Get(nil)
	assert.Tf(t, strings.Contains(err.Error(), "401 - Unauthorized"), "%s", err.Error())

	e = err.(*ResponseError)
	assert.Equal(t, ErrorOneTimePasswordRequired, e.Type)
}
Esempio n. 16
0
func TestFromReader(t *testing.T) {
	raw := `{"testing": 123}`
	reader := strings.NewReader(raw)
	jh, err := NewJsonHelperReader(reader)
	assert.Tf(t, err == nil, "Unexpected error decoding json: %s", err)
	assert.Tf(t, jh.Int("testing") == 123, "Unexpected value in json: %d", jh.Int("testing"))
}
Esempio n. 17
0
func TestClean(t *testing.T) {
	tg := treegen.New()
	treeSpec := tg.D("foo",
		tg.D("bar",
			tg.D("aleph",
				tg.F("A", tg.B(42, 65537)),
				tg.F("a", tg.B(42, 65537)))))
	srcpath := treegen.TestTree(t, treeSpec)
	defer os.RemoveAll(srcpath)
	srcStore, err := fs.NewLocalStore(srcpath)
	assert.T(t, err == nil)

	tg = treegen.New()
	treeSpec = tg.D("foo",
		tg.D("bar",
			tg.D("aleph",
				tg.F("A", tg.B(42, 65537)),
				tg.F("a", tg.B(42, 65537))),
			tg.D("beth",
				tg.F("B", tg.B(43, 65537)),
				tg.F("b", tg.B(43, 65537))),
			tg.D("jimmy",
				tg.F("G", tg.B(44, 65537)),
				tg.F("g", tg.B(44, 65537)))),
		tg.D("baz",
			tg.D("uno",
				tg.F("1", tg.B(1, 65537)),
				tg.F("I", tg.B(1, 65537))),
			tg.D("dos",
				tg.F("2", tg.B(11, 65537)),
				tg.F("II", tg.B(11, 65537))),
			tg.D("tres",
				tg.F("3", tg.B(111, 65537)),
				tg.F("III", tg.B(111, 65537)))))
	dstpath := treegen.TestTree(t, treeSpec)
	defer os.RemoveAll(dstpath)
	dstStore, err := fs.NewLocalStore(dstpath)
	assert.T(t, err == nil)

	onePath := dstStore.Resolve(filepath.Join("foo", "baz", "uno", "1"))
	_, err = os.Stat(onePath)
	assert.Tf(t, err == nil, "%v", err)

	patchPlan := NewPatchPlan(srcStore, dstStore)
	failedCmd, err := patchPlan.Exec()
	assert.Tf(t, failedCmd == nil, "%v", failedCmd)
	assert.Tf(t, err == nil, "%v", err)

	errors := make(chan error, 10)
	patchPlan.Clean(errors)
	close(errors)
	for err := range errors {
		assert.Tf(t, err == nil, "%v", err)
	}

	onePath = dstStore.Resolve(filepath.Join("foo", "baz", "uno", "1"))
	_, err = os.Stat(onePath)
	assert.Tf(t, err != nil, "%v", err)
}
Esempio n. 18
0
func TestJsonPathNotation(t *testing.T) {
	// Now lets test xpath type syntax
	assert.Tf(t, jh.Int("/MaxSize") == 1048576, "get int, test capitalization? ")
	assert.Tf(t, jh.String("/nested/nest") == "string2", "should get string %s", jh.String("/nested/nest"))
	assert.Tf(t, jh.String("/nested/list[0]") == "value", "get string from array")
	// note this one has period in name
	assert.Tf(t, jh.String("/period.name") == "value", "test period in name ")
}
Esempio n. 19
0
func TestLexRegex(t *testing.T) {
	tok := token(` /^stats\./i `, LexRegex)
	assert.Tf(t, tok.T == TokenRegex && tok.V == `/^stats\./i`, "%v", tok)
	tok = token(` /^[a-z0-9_-]{3,16}$/ `, LexRegex)
	assert.Tf(t, tok.T == TokenRegex && tok.V == `/^[a-z0-9_-]{3,16}$/`, "%v", tok)
	tok = token(` /<TAG\b[^>]*>(.*?)</TAG>/ `, LexRegex)
	assert.Tf(t, tok.T == TokenRegex && tok.V == `/<TAG\b[^>]*>(.*?)</TAG>/`, "%v", tok)
}
Esempio n. 20
0
func TestManPageParser_Parse(t *testing.T) {
	doc := `NAME
    say-hello - Say hello to current user

DESCRIPTION
    Print out hello to current user
    one more line

OPTIONS
    -n, --name=[NAME]
        Say hello to the given name
    -v, --verbose
        Run in verbose mode
    -g, --greeting=Hello
        Say hello with a custom type of greeting
`
	p := &manPageParser{doc}
	mp, err := p.Parse()

	assert.Equal(t, nil, err)
	assert.Equal(t, "say-hello", mp.Name)
	assert.Equal(t, "Say hello to current user", mp.Usage)
	assert.Equal(t, "Print out hello to current user\n   one more line", mp.Description)
	assert.Equal(t, 3, len(mp.Flags))

	stringFlag, ok := mp.Flags[0].(task.StringFlag)
	assert.Tf(t, ok, "Can't convert flag to task.StringFlag")
	assert.Equal(t, "n, name", stringFlag.Name)
	assert.Equal(t, "", stringFlag.Value)
	assert.Equal(t, "Say hello to the given name", stringFlag.Usage)

	boolFlag, ok := mp.Flags[1].(task.BoolFlag)
	assert.Tf(t, ok, "Can't convert flag to task.BoolFlag")
	assert.Equal(t, "v, verbose", boolFlag.Name)
	assert.Equal(t, "Run in verbose mode", boolFlag.Usage)

	stringFlag, ok = mp.Flags[2].(task.StringFlag)
	assert.Tf(t, ok, "Can't convert flag to task.StringFlag")
	assert.Equal(t, "g, greeting", stringFlag.Name)
	assert.Equal(t, "Hello", stringFlag.Value)
	assert.Equal(t, "Say hello with a custom type of greeting", stringFlag.Usage)

	doc = `Name
    say-hello - Say hello to current user

Description
    Print out hello to current user
`
	p = &manPageParser{doc}
	mp, err = p.Parse()

	assert.Equal(t, nil, err)
	assert.Equal(t, "", mp.Name)
	assert.Equal(t, "", mp.Usage)
	assert.Equal(t, "", mp.Description)
	assert.Equal(t, 0, len(mp.Flags))
}
Esempio n. 21
0
func TestLeftRight(t *testing.T) {
	t.Parallel()
	l, r, hasLeft := LeftRight("`table`.`column`")
	assert.Tf(t, l == "table" && hasLeft, "no quote: %s", l)
	assert.Tf(t, r == "column", "no quote: %s", l)
	l, r, hasLeft = LeftRight("`table.column`")
	assert.Tf(t, l == "table" && hasLeft, "no quote: %s", l)
	assert.Tf(t, r == "column", "no quote: %s", l)
}
Esempio n. 22
0
func TestTree(t *testing.T, g Generated) string {
	tempdir, err := ioutil.TempDir("", PREFIX)
	assert.Tf(t, err == nil, "Fail to create temp dir")

	err = Fab(tempdir, g)
	assert.Tf(t, err == nil, "Fail to fab tree: %v", err)

	return tempdir
}
Esempio n. 23
0
func TestCoerceNumbers(t *testing.T) {
	for _, cv := range numberCoerceTests {
		v, err := ToValue(cv.v)
		assert.Tf(t, err == nil, "Nil err? %v", err)
		floatVal, _ := ToFloat64(v.Rv())
		//assert.Tf(t, ok, "Should be ok")
		assert.Tf(t, CloseEnuf(floatVal, cv.f), "should be == expect %v but was: %v", cv.f, floatVal)
	}
}
Esempio n. 24
0
func TestCoerceInts(t *testing.T) {
	for _, cv := range intTests {
		v, err := ToValue(cv.v)
		assert.Tf(t, err == nil, "Nil err? %v", err)
		intVal, ok := ToInt64(v.Rv())
		assert.Tf(t, ok, "Should be ok: %#v   %v", cv, intVal)
		assert.Tf(t, intVal == cv.i, "should be == expect %v but was: %v  %#v", cv.i, intVal, cv)
	}
}
Esempio n. 25
0
func DoTestSetModeNew(t *testing.T, mkrepo repoMaker) {
	tg := treegen.New()
	treeSpec := tg.D("foo",
		tg.D("bar",
			tg.D("aleph",
				tg.F("A", tg.B(42, 65537)),
				tg.F("a", tg.B(42, 65537)))))
	srcpath := treegen.TestTree(t, treeSpec)
	os.Chmod(filepath.Join(srcpath, "foo", "bar", "aleph", "A"), 0765)
	os.Chmod(filepath.Join(srcpath, "foo", "bar"), 0711)
	defer os.RemoveAll(srcpath)
	srcRepo := mkrepo(t)
	defer srcRepo.Close()
	srcStore, err := fs.NewLocalStore(srcpath, srcRepo)
	assert.T(t, err == nil)

	tg = treegen.New()
	treeSpec = tg.D("foo")
	dstpath := treegen.TestTree(t, treeSpec)
	defer os.RemoveAll(dstpath)
	dstRepo := mkrepo(t)
	defer dstRepo.Close()
	dstStore, err := fs.NewLocalStore(dstpath, dstRepo)
	assert.T(t, err == nil)

	patchPlan := NewPatchPlan(srcStore, dstStore)
	failedCmd, err := patchPlan.Exec()
	assert.Tf(t, failedCmd == nil, "%v", failedCmd)
	assert.Tf(t, err == nil, "%v", err)

	errors := make(chan os.Error)
	go func() {
		patchPlan.Clean(errors)
		close(errors)
	}()
	for err := range errors {
		assert.Tf(t, err == nil, "%v", err)
	}

	errors = make(chan os.Error)
	go func() {
		patchPlan.SetMode(errors)
		close(errors)
	}()
	for err := range errors {
		assert.Tf(t, err == nil, "%v", err)
	}

	fileinfo, err := os.Stat(filepath.Join(dstpath, "foo", "bar", "aleph", "A"))
	assert.T(t, fileinfo != nil)
	assert.Equal(t, uint32(0765), fileinfo.Permission())

	fileinfo, err = os.Stat(filepath.Join(dstpath, "foo", "bar"))
	assert.T(t, fileinfo != nil)
	assert.Equal(t, uint32(0711), fileinfo.Permission())
}
Esempio n. 26
0
func TestSqlUpdate(t *testing.T) {
	t.Parallel()
	sql := `UPDATE users SET name = "was_updated", [deleted] = true WHERE id = "user815"`
	req, err := ParseSql(sql)
	assert.Tf(t, err == nil && req != nil, "Must parse: %s  \n\t%v", sql, err)
	up, ok := req.(*SqlUpdate)
	assert.Tf(t, ok, "is SqlUpdate: %T", req)
	assert.Tf(t, up.Table == "users", "has users: %v", up.Table)
	assert.Tf(t, len(up.Values) == 2, "%v", up)
}
Esempio n. 27
0
func TestSqlAggregateTypeSelect(t *testing.T) {
	t.Parallel()
	sql := `select avg(char_length(title)) from article`
	req, err := ParseSql(sql)
	assert.Tf(t, err == nil && req != nil, "Must parse: %s  \n\t%v", sql, err)
	sel, ok := req.(*SqlSelect)
	assert.Tf(t, ok, "is SqlSelect: %T", req)
	sel.Rewrite()
	assert.Tf(t, sel.IsAggQuery(), "wanted IsAggQuery()==true but got false")
}
Esempio n. 28
0
func verifySqlDelete(t *testing.T, sql string, source *datasource.ContextSimple) {

	sqlVm, err := NewSqlVm(sql)
	assert.Tf(t, err == nil, "Should not err %v", err)
	assert.Tf(t, sqlVm != nil, "Should create vm & parse sql %v", sqlVm)

	err = sqlVm.ExecuteDelete(source, source)
	assert.Tf(t, err == nil, "non nil err: %v", err)

}
Esempio n. 29
0
func verifyIdentity(t *testing.T, input, expects string, isIdentity bool) {
	l := NewSqlLexer(input)
	assert.Tf(t, isIdentity == l.isIdentity(), "Expected %s to be %v identity", input, isIdentity)
	LexIdentifier(l)
	tok := l.NextToken()
	if isIdentity {
		assert.T(t, tok.T == TokenIdentity)
		assert.Tf(t, tok.V == expects, "expected %s got %v", expects, tok.V)
	}
}
Esempio n. 30
0
func DoTestParentRefs(t *testing.T, repo fs.NodeRepo) {
	tg := treegen.New()
	treeSpec := tg.D("foo",
		tg.D("bar",
			tg.D("aleph",
				tg.F("A", tg.B(42, 65537)),
				tg.F("a", tg.B(42, 65537))),
			tg.D("beth",
				tg.F("B", tg.B(43, 65537)),
				tg.F("b", tg.B(43, 65537))),
			tg.D("jimmy",
				tg.F("G", tg.B(44, 65537)),
				tg.F("g", tg.B(44, 65537)))),
		tg.D("baz",
			tg.D("uno",
				tg.F("1", tg.B(1, 65537)),
				tg.F("I", tg.B(1, 65537))),
			tg.D("dos",
				tg.F("2", tg.B(11, 65537)),
				tg.F("II", tg.B(11, 65537))),
			tg.D("tres",
				tg.F("3", tg.B(111, 65537)),
				tg.F("III", tg.B(111, 65537)))))

	path := treegen.TestTree(t, treeSpec)
	defer os.RemoveAll(path)

	foo, errors := fs.IndexDir(filepath.Join(path, "foo"), repo)
	assert.Equalf(t, 0, len(errors), "%v", errors)

	rootCount := 0
	fs.Walk(foo, func(node fs.Node) bool {
		switch node.(type) {
		case fs.Dir:
			dir := node.(fs.Dir)
			if _, hasParent := dir.Parent(); !hasParent {
				rootCount++
			}
			break
		case fs.File:
			file := node.(fs.File)
			_, hasParent := file.Parent()
			assert.Tf(t, hasParent, "%v is root?!", file.Info())
			break
		case fs.Block:
			block := node.(fs.Block)
			_, hasParent := block.Parent()
			assert.Tf(t, hasParent, "%v is root?!", block.Info())
			break
		}
		return true
	})

	assert.Equal(t, 1, rootCount)
}