// GenerateTestMain returns the source code for a test program that will run // the specified test functions from the specified package. func GenerateTestMain(packageName string, funcs *set.StringSet) string { var funcVec vector.StringVector for val := range funcs.Iter() { funcVec.Push(val) } result := "" result += "package main\n\n" result += "import \"testing\"\n" if funcVec.Len() > 0 { result += fmt.Sprintf("import \"./%s\"\n\n", packageName) } result += "var tests = []testing.Test {\n" for _, val := range funcVec.Data() { result += fmt.Sprintf("\ttesting.Test{\"%s\", %s.%s},\n", val, packageName, val) } result += "}\n\n" result += "func main() {\n" result += "\ttesting.Main(tests)\n" result += "}\n" return result }
func (p *Pipeline) Import(client oauth2_client.OAuth2Client, ds DataStoreService, cs ContactsService, csSettings ContactsServiceSettings, dsocialUserId, meContactId string, allowAdd, allowDelete, allowUpdate bool) (err os.Error) { fmt.Printf("[PIPELINE]: Starting importing...\n") if !csSettings.AllowRetrieveContactInfo() || !cs.CanImportContactsOrGroups() { // do nothing } else { groupMappings := make(map[string]*list.List) contactChangesetIds := new(vector.StringVector) groupChangesetIds := new(vector.StringVector) if cs.CanRetrieveContacts() { err = p.importContacts(client, ds, cs, dsocialUserId, allowAdd, allowDelete, allowUpdate, groupMappings, contactChangesetIds) } else if cs.CanRetrieveConnections() { err = p.importConnections(client, ds, cs, dsocialUserId, allowAdd, allowDelete, allowUpdate, groupMappings, contactChangesetIds) } if err == nil && cs.CanRetrieveGroups() { err = p.importGroups(client, ds, cs, dsocialUserId, allowAdd, allowDelete, allowUpdate, groupMappings, groupChangesetIds) } if contactChangesetIds.Len() > 0 || groupChangesetIds.Len() > 0 { settings, _ := ds.RetrieveAllContactsServiceSettingsForUser(dsocialUserId) err = p.queueContactChangeSetsToApply(ds, cs, csSettings, settings, dsocialUserId, contactChangesetIds) if err == nil { err = p.queueGroupChangeSetsToApply(ds, cs, csSettings, settings, dsocialUserId, groupChangesetIds) } } } fmt.Printf("[PIPELINE]: Done importing.\n") return }
func ExecutionModelSpec(c nanospec.Context) { c.Specify("Specs with children, but without siblings, are executed fully on one run", func() { c.Specify("Case: no children", func() { runSpecWithContext(DummySpecWithNoChildren, newInitialContext()) c.Expect(testSpy).Equals("root") }) c.Specify("Case: one child", func() { runSpecWithContext(DummySpecWithOneChild, newInitialContext()) c.Expect(testSpy).Equals("root,a") }) c.Specify("Case: nested children", func() { runSpecWithContext(DummySpecWithNestedChildren, newInitialContext()) c.Expect(testSpy).Equals("root,a,aa") }) }) c.Specify("Specs with siblings are executed only one sibling at a time", func() { c.Specify("Case: on initial run, the 1st child is executed", func() { runSpecWithContext(DummySpecWithTwoChildren, newInitialContext()) c.Expect(testSpy).Equals("root,a") }) c.Specify("Case: explicitly execute the 1st child", func() { runSpecWithContext(DummySpecWithTwoChildren, newExplicitContext([]int{0})) c.Expect(testSpy).Equals("root,a") }) c.Specify("Case: explicitly execute the 2nd child", func() { runSpecWithContext(DummySpecWithTwoChildren, newExplicitContext([]int{1})) c.Expect(testSpy).Equals("root,b") }) }) c.Specify("Specs with nested siblings: eventually all siblings are executed, one at a time, in isolation", func() { r := NewRunner() r.AddSpec(DummySpecWithMultipleNestedChildren) // Execute manually instead of calling Run(), in order to avoid running // the specs multi-threadedly, which would mess up the test spy. runs := new(vector.StringVector) for r.hasScheduledTasks() { resetTestSpy() r.executeNextScheduledTask() runs.Push(testSpy) } sort.Sort(runs) c.Expect(runs.Len()).Equals(5) c.Expect(runs.At(0)).Equals("root,a,aa") c.Expect(runs.At(1)).Equals("root,a,ab") c.Expect(runs.At(2)).Equals("root,b,ba") c.Expect(runs.At(3)).Equals("root,b,bb") c.Expect(runs.At(4)).Equals("root,b,bc") }) }
func (self *Regex) Matches(s string) []string { res := new(vector.StringVector) self.l.StartString(s) for !self.l.Eof() { if self.l.Next() == 0 { res.Push(self.l.String()) } } return []string(*res.Slice(0, res.Len())) }
func (self *Regex) Replace(s string, f func(string) string) string { res := new(vector.StringVector) buf := bytes.Runes([]byte(s)) last := 0 self.l.StartString(s) for !self.l.Eof() { if self.l.Next() == 0 { res.Push(string(buf[last:self.l.Pos()])) res.Push(f(self.l.String())) last = self.l.Pos() + self.l.Len() } } res.Push(string(buf[last:])) return strings.Join([]string(*res.Slice(0, res.Len())), "") }
func (p *Trie) GetDotString() string { rsrc := rand.NewSource(140209) rgen := rand.New(rsrc) outStr := "digraph Trie {" vec := new(vector.StringVector) p.outputDot(vec, 0, -1, rgen) cnt := vec.Len() for i := 0; i < cnt; i++ { outStr = strings.Join([]string{outStr, vec.At(i)}, "\n") } return strings.Join([]string{outStr, "}"}, "\n") }
// List all commands, one by each line, sorted alphabetically func gtplist_commands(obj *GTPObject) *GTPCommand { signature := []int{} f := func(object *GTPObject, params []interface{}) (result string, quit bool, err Error) { result = "" var cmdVector vector.StringVector for cmdName, _ := range obj.commands { cmdVector.Push(cmdName) } sort.SortStrings(sort.StringArray(cmdVector)) result += cmdVector[0] for i := 1; i < cmdVector.Len(); i++ { result += "\n" + cmdVector.At(i) } return result, false, nil } return >PCommand{Signature: signature, Func: f, } }
// loads ascii arts from data directory func (self *AsciiArtGallery) goLoadAsciiArts() { self.loadedArts = false go func() { files := vector.StringVector{} entries, err := ioutil.ReadDir("data/ascii") if err != nil { panic("Cannot read files from data/ascii") } for _, f := range entries { if strings.HasSuffix(f.Name(), ".dat") { files.Push(path.Join("data/ascii", f.Name())) } } self.arts = make([]IAsciiArt, files.Len()) self.artfiles = files self.loadedArtsChan <- true }() }
func (exchange *Exchange) handleTick(t int64) { removeTheseUnreadyQueues := new(vector.StringVector) for toAddress, messageQueue := range exchange.messageQueues { for i := 0; i < messageQueue.Len(); i++ { msg := messageQueue.At(i).(Message) if msg.timeout < t { exchange.logf(LogLevelDebug, "> %v %v %v %v", len(msg.Body), msg.TimeoutSeconds, msg.ToAddress, msg.ReplyAddress) exchange.logf(LogLevelDebug, " send timeout") messageQueue.Delete(i) i-- } } if messageQueue.Len() == 0 { removeTheseUnreadyQueues.Push(toAddress) } } for i := 0; i < removeTheseUnreadyQueues.Len(); i++ { exchange.messageQueues[removeTheseUnreadyQueues.At(i)] = nil, false } removeTheseReadyStates := new(vector.StringVector) for onAddress, readyStateQueue := range exchange.readyStateQueues { for i := 0; i < readyStateQueue.Len(); i++ { readyState := readyStateQueue.At(i).(*readyState) if readyState.timeout < t { exchange.logf(LogLevelDebug, "* ready timeout %v", onAddress) if !readyState.timeoutReceived { readyState.messageChan <- Message{"", "", 0, "", 0} readyState.timeoutReceived = true } readyStateQueue.Delete(i) i-- } } if readyStateQueue.Len() == 0 { removeTheseReadyStates.Push(onAddress) } } for i := 0; i < removeTheseReadyStates.Len(); i++ { exchange.readyStateQueues[removeTheseReadyStates.At(i)] = nil, false } }
func (p *Pipeline) queueGroupChangeSetsToApply(ds DataStoreService, cs ContactsService, csSettings ContactsServiceSettings, settings []ContactsServiceSettings, dsocialUserId string, changesetIds *vector.StringVector) (err os.Error) { if changesetIds == nil || changesetIds.Len() == 0 || settings == nil || len(settings) == 0 { return } thisServiceName := cs.ServiceId() thisServiceId := csSettings.Id() ids := []string(*changesetIds) for _, setting := range settings { if setting.Id() == thisServiceId && thisServiceName == setting.ContactsServiceId() { // if we import from this service, don't export to it continue } if _, err2 := ds.AddGroupChangeSetsToApply(dsocialUserId, setting.Id(), setting.ContactsServiceId(), ids); err2 != nil { if err == nil { err = err2 } break } } return }
func TestMultiFind(t *testing.T) { trie := NewTrie() // these are part of the matches for the word 'hyphenation' trie.AddString(`hyph`) trie.AddString(`hen`) trie.AddString(`hena`) trie.AddString(`henat`) expected := new(vector.StringVector) expected.Push(`hyph`) found := trie.AllSubstrings(`hyphenation`) if found.Len() != expected.Len() { t.Errorf("expected %v but found %v", *expected, *found) } expected.Cut(0, expected.Len()) expected.Push(`hen`) expected.Push(`hena`) expected.Push(`henat`) found = trie.AllSubstrings(`henation`) if found.Len() != expected.Len() { t.Errorf("expected %v but found %v", *expected, *found) } }
// As gtpkomoku_sourcen, except that it makes replaces the board with a copy of it in each move. This is used to debug // Board.Copy() func gtpkomoku_sourceforkn(obj *GTPObject) *GTPCommand { signature := []int{GTPString, GTPInt} f := func(object *GTPObject, params []interface{}) (result string, quit bool, err Error) { filename, _ := params[0].(string) n := int(params[1].(uint)) file, er := os.Open(filename, os.O_RDONLY, 0) if er != nil { return fmt.Sprintf("error: '%s'", err), false, NewIOError(er) } input := bufio.NewReader(file) var lines vector.StringVector line, er := input.ReadString('\n') lines.Push(line) for er != os.EOF { lines.Push(line) line, er = input.ReadString('\n') } length := lines.Len() line = "" for i := 0; i < length; i++ { line = lines.At(i) if length-i <= n { line = "#" + line } fmt.Printf(line) obj.ai.environment.Game.Board = obj.ai.environment.Game.Board.Copy() lineResult, lineQuit, _ := obj.ExecuteCommand(line) fmt.Printf(lineResult) if lineQuit { return "", true, nil } } fmt.Println("\nend komoku-sourceforkn") return "", false, nil } return >PCommand{Signature: signature, Func: f, } }
func ParsePhoneNumber(s string, number *PhoneNumber) { slen := len(s) if slen == 0 { return } number.FormattedNumber = s sv := new(vector.StringVector) start := 0 for i := 0; i < slen; i++ { b := s[i] switch b { case '-', ' ', '.', ')', '_': if start < i { addIfNonSpaces(sv, s[start:i]) } start = i + 1 case '(': for j := i + 1; j < slen; j++ { if s[j] == ')' { if start < i { addIfNonSpaces(sv, s[start:i]) } addIfNonSpaces(sv, s[i+1:j]) i = j start = j + 1 break } } case 'x', 'X': if start < i { lastChar := s[i-1] if lastChar == 'e' || lastChar == 'E' { continue } p := strings.TrimSpace(s[start:i]) if p != "" { sv.Push(p) } } number.ExtensionNumber = strings.TrimSpace(s[i+1:]) start = slen i = slen break case 't', 'T': l := i - start if l > 2 && strings.ToLower(s[i-2:i+1]) == "ext" { if start < i-2 { p := strings.TrimSpace(s[start : i-2]) if p != "" { sv.Push(p) } } } number.ExtensionNumber = strings.TrimSpace(s[i+1:]) start = slen i = slen break } } if start < slen { p := strings.TrimSpace(s[start:]) if p != "" { sv.Push(p) } } parts := *sv if sv.Len() == 0 { return } at := 0 l := len(parts) if parts[0][0] == '+' { // preferred format is +<country code>-<area code>-<local code> number.CountryCode = parts[0][1:] at++ } else if len(parts[0]) < 3 { // make an assumption that this is a country code number.CountryCode = parts[0] at++ } if l > at+1 { number.AreaCode = parts[at] at++ } if l > at { number.LocalPhoneNumber = strings.Join(parts[at:], "-") } }
func (p *Pipeline) applyGroupChangeSets(client oauth2_client.OAuth2Client, ds DataStoreService, cs ContactsService, csSettings ContactsServiceSettings, dsocialUserId, meContactId string) (err os.Error) { externalServiceId := csSettings.Id() externalServiceName := csSettings.ContactsServiceId() externalUserId := csSettings.ExternalUserId() applyable, changesets, err := ds.RetrieveGroupChangeSetsToApply(dsocialUserId, externalServiceId, externalServiceName) if err != nil { return } fmt.Printf("[PIPELINE]: Will be applying up to %d changesets from %d applyable\n", len(changesets), len(applyable)) changesetIdsNotApplyable := new(vector.StringVector) changesetIdsApplied := new(vector.StringVector) for _, toApply := range applyable { if err != nil { break } for _, changesetId := range toApply.ChangeSetIds { if err != nil { break } changeset, _ := changesets[changesetId] if changeset != nil { isMe := changeset.RecordId == meContactId canCreate, canUpdate, canDelete := cs.CanCreateGroup(isMe), cs.CanUpdateGroup(isMe), cs.CanDeleteGroup(isMe) if !canCreate && !canUpdate && !canDelete { changesetIdsNotApplyable.Push(changeset.Id) continue } fmt.Printf("[PIPELINE]: handling changeset id %s\n", changeset.Id) isCreate, isUpdate, isDelete := false, false, false if len(changeset.Changes) > 1 { isUpdate = true } else if len(changeset.Changes) == 1 { switch changeset.Changes[0].ChangeType { case dm.CHANGE_TYPE_CREATE: isCreate = true case dm.CHANGE_TYPE_ADD: if changeset.Changes[0].Path == nil || len(changeset.Changes[0].Path) == 0 { isCreate = true } else { isUpdate = true } case dm.CHANGE_TYPE_UPDATE: isUpdate = true case dm.CHANGE_TYPE_DELETE: if changeset.Changes[0].Path == nil || len(changeset.Changes[0].Path) == 0 { isDelete = true } else { isUpdate = true } } } if !(isCreate && canCreate) && !(isUpdate && canUpdate) && !(isDelete && canDelete) { changesetIdsNotApplyable.Push(changeset.Id) continue } dsocialGroupId := changeset.RecordId if isDelete { err = p.handleDeleteGroup(client, ds, cs, dsocialUserId, externalServiceId, externalUserId, dsocialGroupId) } else if isCreate { err = p.handleCreateGroup(client, ds, cs, dsocialUserId, dsocialGroupId) } else { // must be update err = p.handleUpdateGroup(client, ds, cs, dsocialUserId, externalServiceId, externalUserId, dsocialGroupId, changeset) } changesetIdsApplied.Push(changeset.Id) } } } if err == nil { fmt.Printf("[PIPELINE]: Skipped applying %d changesets\n", changesetIdsNotApplyable.Len()) err = p.markGroupChangeSetsNotApplyable(ds, dsocialUserId, externalServiceId, externalServiceName, []string(*changesetIdsNotApplyable)) if err == nil { err = ds.RemoveContactChangeSetsToApply(dsocialUserId, externalServiceId, externalServiceName, []string(*changesetIdsApplied)) } } fmt.Printf("[PIPELINE]: Done applying group changesets\n") return }
func main() { flag.Parse() if flag.NArg() != 2 { printUsageAndExit() } command := flag.Arg(0) if command != "build" && command != "test" { printUsageAndExit() } // Grab dependency and file information for every local package, starting // with the specified one. We consider a package local if it starts with "./". requiredFiles := make(map[string]*set.StringSet) packageDeps := make(map[string]*set.StringSet) specifiedPackage := flag.Arg(1) var remainingPackages vector.StringVector remainingPackages.Push(specifiedPackage) for remainingPackages.Len() > 0 { packageName := remainingPackages.Pop() // Have we already processed this directory? _, alreadyDone := packageDeps[packageName] if alreadyDone { continue } dir := "./" + packageName dirInfo := build.GetDirectoryInfo(dir) if dirInfo.PackageName == "" { fmt.Printf("Couldn't find .go files to build in directory: %s\n", dir) os.Exit(1) } // Stash information about this package, and add its local dependencies to // the queue. requiredFiles[packageName] = dirInfo.Files packageDeps[packageName] = dirInfo.Deps // If we're testing and this is the package under test, also add its test // files and dependencies. if packageName == specifiedPackage && command == "test" { requiredFiles[packageName].Union(dirInfo.TestFiles) packageDeps[packageName].Union(dirInfo.TestDeps) } for dep := range packageDeps[packageName].Iter() { remainingPackages.Push(dep) } } // Order the packages by their dependencies. totalOrder := deps.BuildTotalOrder(packageDeps) fmt.Println("Found these packages to compile:") for _, packageName := range totalOrder { fmt.Printf(" %s\n", packageName) } // Create a directory to hold outputs, deleting the old one first. os.RemoveAll("igo-out") os.Mkdir("igo-out", 0700) // Compile each of the packages in turn. for _, currentPackage := range totalOrder { fmt.Printf("\nCompiling package: %s\n", currentPackage) compileFiles(requiredFiles[currentPackage], currentPackage) } // If this is a binary, also link it. if build.GetDirectoryInfo(specifiedPackage).PackageName == "main" { linkBinary(specifiedPackage) } // If we're testing, create a test runner, build it, and run it. if command == "test" { const outputFile = "igo-out/test_runner.go" testFuncs := build.GetDirectoryInfo(specifiedPackage).TestFuncs code := test.GenerateTestMain(specifiedPackage, testFuncs) err := ioutil.WriteFile("igo-out/test_runner.go", strings.Bytes(code), 0600) if err != nil { panic(err) } var files set.StringSet files.Insert("igo-out/test_runner.go") compileFiles(&files, "test_runner") linkBinary("test_runner") if !executeCommand("igo-out/test_runner", []string{}, "") { os.Exit(1) } } }
func TestMultiFindValue(t *testing.T) { trie := NewTrie() // these are part of the matches for the word 'hyphenation' trie.AddPatternString(`hy3ph`) trie.AddPatternString(`he2n`) trie.AddPatternString(`hena4`) trie.AddPatternString(`hen5at`) v1 := &vector.IntVector{0, 3, 0, 0} v2 := &vector.IntVector{0, 2, 0} v3 := &vector.IntVector{0, 0, 0, 4} v4 := &vector.IntVector{0, 0, 5, 0, 0} expectStr := new(vector.StringVector) expectVal := new(vector.Vector) // contains elements of type *vector.IntVector expectStr.Push(`hyph`) expectVal.Push(v1) found, values := trie.AllSubstringsAndValues(`hyphenation`) if found.Len() != expectStr.Len() { t.Errorf("expected %v but found %v", *expectStr, *found) } if values.Len() != expectVal.Len() { t.Errorf("Length mismatch: expected %v but found %v", *expectVal, *values) } for i := 0; i < found.Len(); i++ { if found.At(i) != expectStr.At(i) { t.Errorf("Strings content mismatch: expected %v but found %v", *expectStr, *found) break } } for i := 0; i < values.Len(); i++ { ev := expectVal.At(i).(*vector.IntVector) fv := values.At(i).(*vector.IntVector) if ev.Len() != fv.Len() { t.Errorf("Value length mismatch: expected %v but found %v", *ev, *fv) break } for i := 0; i < ev.Len(); i++ { if ev.At(i) != fv.At(i) { t.Errorf("Value mismatch: expected %v but found %v", *ev, *fv) break } } } expectStr.Cut(0, expectStr.Len()) expectVal.Cut(0, expectVal.Len()) expectStr.AppendVector(&vector.StringVector{`hen`, `hena`, `henat`}) expectVal.Push(v2) expectVal.Push(v3) expectVal.Push(v4) found, values = trie.AllSubstringsAndValues(`henation`) if found.Len() != expectStr.Len() { t.Errorf("expected %v but found %v", *expectStr, *found) } if values.Len() != expectVal.Len() { t.Errorf("Length mismatch: expected %v but found %v", *expectVal, *values) } for i := 0; i < found.Len(); i++ { if found.At(i) != expectStr.At(i) { t.Errorf("Strings content mismatch: expected %v but found %v", *expectStr, *found) break } } for i := 0; i < values.Len(); i++ { ev := expectVal.At(i).(*vector.IntVector) fv := values.At(i).(*vector.IntVector) if ev.Len() != fv.Len() { t.Errorf("Value length mismatch: expected %v but found %v", *ev, *fv) break } for i := 0; i < ev.Len(); i++ { if ev.At(i) != fv.At(i) { t.Errorf("Value mismatch: expected %v but found %v", *ev, *fv) break } } } }