How to use Check method of host Package

Best Syzkaller code snippet using host.Check

helpers.go

Source:helpers.go Github

copy

Full Screen

...14 CurrentDb string `json:"CurrentDb"`15}16// CommandOrchestrator is the function that all commands call to be executed. It orchestrates17// validation and configuration for each command.18func CommandOrchestrator(initCommand string, args []string, prevArgCheckMap map[string]bool, checkDbRequired bool, validators ...map[string]bool) {19 // get user's $HOME dir20 home, err := homedir.Dir()21 CheckErr("Could not get $HOME dir:", err)22 // get currently set host23 currentHost, err := GetHostState(home)24 CheckErr("Could not get currently set host:", err)25 // check host config exists26 CheckErr(fmt.Sprintf("Could not get config for host %s", currentHost.Host), CheckHostConfig(currentHost.Host))27 // if config exists, get settings for current host28 hostSettings := viper.GetStringMapString(currentHost.Host)29 // mysql30 if hostSettings["platform"] == "mysql" {31 // find 'mysql' executable path32 mysqlPath, err := exec.LookPath("mysql")33 if err != nil {34 fmt.Println(err)35 os.Exit(1)36 }37 // isClauseNeedingDb checks if args includes item that requires 'use db'38 var isClauseNeedingDb bool39 if checkDbRequired {40 // if true, the option to not use db exists..41 isClauseNeedingDb = CheckArgsInclude(args, validators...)42 if isClauseNeedingDb {43 if currentHost.CurrentDb == "" {44 fmt.Println("Please use 'ssql use [dbName]' first")45 os.Exit(1)46 }47 }48 } else {49 // else, there is no option, db is needed50 // assert that a db is set51 isClauseNeedingDb = true52 if currentHost.CurrentDb == "" {53 fmt.Println("Please use 'ssql use [dbName]' first")54 os.Exit(1)55 }56 }57 // build query and query command58 dbQueryBase := initCommand59 // select does not need to wrap any values in quotes60 //prevArgCheck := map[string]bool{"placeholder": false}61 dbQueryBase = BuildDbQuery(args, prevArgCheckMap, dbQueryBase)62 var dbQuery string63 if !isClauseNeedingDb {64 dbQuery = dbQueryBase65 } else {66 dbQuery = fmt.Sprintf(`USE %s; %s;`, currentHost.CurrentDb, dbQueryBase)67 }68 query := CreateMysqlQueryCommand(dbQuery, hostSettings, mysqlPath)69 // run the command70 if err := query.Run(); err != nil {71 CheckErr(fmt.Sprintf("Could not run mysql command for query %s", dbQuery), err)72 }73 // postgres74 } else {75 // TODO: else do postgres stuff(coming soon)76 }77}78// GetLongDescription creates a long description for the passed command.79func GetLongDescription(commandName string) string {80 return fmt.Sprintf(`The %s command has most of the usual functionality81provided by the sql %s statement.`, commandName, commandName)82}83// GetHostState reads the currently set host from the user's84// $HOME/.ssqlHostState file and returns the unmarshaled json85// string as a data structure.86func GetHostState(home string) (stateData hostState, err error) {87 hostStateFile, err := ioutil.ReadFile(home + "/.ssqlHostState")88 stateData = hostState{}89 _ = json.Unmarshal([]byte(hostStateFile), &stateData)90 return stateData, err91}92// SetHostState uses the user's $HOME path and the user's desired93// host retrieved from args to create a state containing which94// host from the user's config file should be used. The state is95// stored in the file $HOME/.ssqlHostState.96func SetHostState(home, host, platform, currentDb string) (err error) {97 hostData := hostState{98 Host: host,99 Platform: platform,100 CurrentDb: currentDb, // current db will always default to empty101 }102 json, err := json.MarshalIndent(hostData, "", " ")103 if err != nil {104 return err105 }106 _ = ioutil.WriteFile(home+"/.ssqlHostState", json, 0644)107 return108}109// CheckHostConfig takes the user's desired host from args and asserts110// that it is available in the user's .ssql config file.111func CheckHostConfig(desiredHost string) error {112 if viper.IsSet(desiredHost) == false {113 return fmt.Errorf("Host '%s' is not configured. Please make sure the desired host is configured in your .ssql config file.", desiredHost)114 }115 return nil116}117// CheckErr is a general function that can be used to check for errors. If118// an error is present, it will output the error to stdout and terminate the119// program.120func CheckErr(fromMsg string, err error) {121 if e := err; err != nil {122 fmt.Println(fromMsg, e)123 os.Exit(1)124 }125}126// CreateMysqlQueryCommand creates the mysql command out of the user's host config127// and passed args.128func CreateMysqlQueryCommand(dbQuery string, hostSettings map[string]string, commandPath string) *exec.Cmd {129 if hostSettings["defaults_file"] != "" {130 dbUser := fmt.Sprintf(`-u%s`, hostSettings["user"])131 dbOptionFile := fmt.Sprintf(`--defaults-file=%s`, hostSettings["defaults_file"])132 dbCmd := &exec.Cmd{133 Path: commandPath,134 Args: []string{commandPath, dbOptionFile, `-h`, hostSettings["host"],135 `-P`, hostSettings["port"], dbUser, `-e`, dbQuery},136 Stdout: os.Stdout,137 Stderr: os.Stderr,138 }139 return dbCmd140 } else {141 dbUser := fmt.Sprintf(`-u%s`, hostSettings["user"])142 dbPassword := fmt.Sprintf(`-p%s`, hostSettings["password"])143 dbCmd := &exec.Cmd{144 Path: commandPath,145 Args: []string{commandPath, `-h`, hostSettings["host"],146 `-P`, hostSettings["port"], dbUser, dbPassword, `-e`, dbQuery},147 Stdout: os.Stdout,148 Stderr: os.Stderr,149 }150 return dbCmd151 }152}153// CheckArgsInclude is a generic variadic function that checks to see if an array(args)154// contains an element or elements contained in n maps. The maps are checked concurrently155// using goroutines.156func CheckArgsInclude(args []string, validators ...map[string]bool) bool {157 countGoroutine := len(validators)158 c := make(chan bool)159 // initiate n goroutines160 for i := 0; i < len(validators); i++ {161 go checkArgsIncludeChild(args, validators[i], c)162 }163 for countToComplete := 0; countToComplete < countGoroutine; countToComplete++ {164 result := <-c165 if result == true {166 return result167 }168 }169 return false170}171// checkArgsIncludeChild checks if each arg is present in a map and172// writes the results to a channel read by CheckArgsInclude.173func checkArgsIncludeChild(args []string, validator map[string]bool, c chan bool) {174 for iArg := 0; iArg < len(args); iArg++ {175 if validator[args[iArg]] == true {176 c <- true177 }178 }179 c <- false180}181// BuildDbQuery uses args passed by the user and builds a db182// query out of them.183func BuildDbQuery(args []string, prevArgCheck map[string]bool, dbQueryBase string) string {184 for i := 0; i < len(args); i++ {185 // if the previous arg is not less than 0(out of index range) and186 // the previous arg is LIKE, wrap pattern in quotes187 if i > 0 && prevArgCheck[args[i-1]] == true {188 dbQueryBase = fmt.Sprintf(`%s "%s"`, dbQueryBase, args[i])189 } else {190 dbQueryBase = dbQueryBase + " " + args[i]191 }192 }193 return dbQueryBase194}...

Full Screen

Full Screen

resource_compute_shared_vpc_test.go

Source:resource_compute_shared_vpc_test.go Github

copy

Full Screen

...12 serviceProject := fmt.Sprintf("tf-test-s-%d", randInt(t))13 hostProjectResourceName := "google_compute_shared_vpc_host_project.host"14 serviceProjectResourceName := "google_compute_shared_vpc_service_project.service"15 vcrTest(t, resource.TestCase{16 PreCheck: func() { testAccPreCheck(t) },17 Providers: testAccProviders,18 Steps: []resource.TestStep{19 {20 Config: testAccComputeSharedVpc_basic(hostProject, serviceProject, org, billingId),21 Check: resource.ComposeTestCheckFunc(22 testAccCheckComputeSharedVpcHostProject(t, hostProject, true),23 testAccCheckComputeSharedVpcServiceProject(t, hostProject, serviceProject, true),24 ),25 },26 // Test import.27 {28 ResourceName: hostProjectResourceName,29 ImportState: true,30 ImportStateVerify: true,31 },32 {33 ResourceName: serviceProjectResourceName,34 ImportState: true,35 ImportStateVerify: true,36 },37 // Use a separate TestStep rather than a CheckDestroy because we need the project to still exist.38 {39 Config: testAccComputeSharedVpc_disabled(hostProject, serviceProject, org, billingId),40 Check: resource.ComposeTestCheckFunc(41 testAccCheckComputeSharedVpcHostProject(t, hostProject, false),42 testAccCheckComputeSharedVpcServiceProject(t, hostProject, serviceProject, false),43 ),44 },45 },46 })47}48func testAccCheckComputeSharedVpcHostProject(t *testing.T, hostProject string, enabled bool) resource.TestCheckFunc {49 return func(s *terraform.State) error {50 config := googleProviderConfig(t)51 found, err := config.NewComputeClient(config.userAgent).Projects.Get(hostProject).Do()52 if err != nil {53 return fmt.Errorf("Error reading project %s: %s", hostProject, err)54 }55 if found.Name != hostProject {56 return fmt.Errorf("Project %s not found", hostProject)57 }58 if enabled != (found.XpnProjectStatus == "HOST") {59 return fmt.Errorf("Project %q shared VPC status was not expected, got %q", hostProject, found.XpnProjectStatus)60 }61 return nil62 }63}64func testAccCheckComputeSharedVpcServiceProject(t *testing.T, hostProject, serviceProject string, enabled bool) resource.TestCheckFunc {65 return func(s *terraform.State) error {66 config := googleProviderConfig(t)67 serviceHostProject, err := config.NewComputeClient(config.userAgent).Projects.GetXpnHost(serviceProject).Do()68 if err != nil {69 if enabled {70 return fmt.Errorf("Expected service project to be enabled.")71 }72 return nil73 }74 if enabled != (serviceHostProject.Name == hostProject) {75 return fmt.Errorf("Wrong host project for the given service project. Expected '%s', got '%s'", hostProject, serviceHostProject.Name)76 }77 return nil78 }...

Full Screen

Full Screen

discovery_test.go

Source:discovery_test.go Github

copy

Full Screen

1package discovery2import (3 "testing"4 "github.com/go-check/check"5)6// Hook up gocheck into the "go test" runner.7func Test(t *testing.T) { check.TestingT(t) }8type DiscoverySuite struct{}9var _ = check.Suite(&DiscoverySuite{})10func (s *DiscoverySuite) TestNewEntry(c *check.C) {11 entry, err := NewEntry("127.0.0.1:2375")12 c.Assert(err, check.IsNil)13 c.Assert(entry.Equals(&Entry{Host: "127.0.0.1", Port: "2375"}), check.Equals, true)14 c.Assert(entry.String(), check.Equals, "127.0.0.1:2375")15 entry, err = NewEntry("[2001:db8:0:f101::2]:2375")16 c.Assert(err, check.IsNil)17 c.Assert(entry.Equals(&Entry{Host: "2001:db8:0:f101::2", Port: "2375"}), check.Equals, true)18 c.Assert(entry.String(), check.Equals, "[2001:db8:0:f101::2]:2375")19 _, err = NewEntry("127.0.0.1")20 c.Assert(err, check.NotNil)21}22func (s *DiscoverySuite) TestParse(c *check.C) {23 scheme, uri := parse("127.0.0.1:2375")24 c.Assert(scheme, check.Equals, "nodes")25 c.Assert(uri, check.Equals, "127.0.0.1:2375")26 scheme, uri = parse("localhost:2375")27 c.Assert(scheme, check.Equals, "nodes")28 c.Assert(uri, check.Equals, "localhost:2375")29 scheme, uri = parse("scheme://127.0.0.1:2375")30 c.Assert(scheme, check.Equals, "scheme")31 c.Assert(uri, check.Equals, "127.0.0.1:2375")32 scheme, uri = parse("scheme://localhost:2375")33 c.Assert(scheme, check.Equals, "scheme")34 c.Assert(uri, check.Equals, "localhost:2375")35 scheme, uri = parse("")36 c.Assert(scheme, check.Equals, "nodes")37 c.Assert(uri, check.Equals, "")38}39func (s *DiscoverySuite) TestCreateEntries(c *check.C) {40 entries, err := CreateEntries(nil)41 c.Assert(entries, check.DeepEquals, Entries{})42 c.Assert(err, check.IsNil)43 entries, err = CreateEntries([]string{"127.0.0.1:2375", "127.0.0.2:2375", "[2001:db8:0:f101::2]:2375", ""})44 c.Assert(err, check.IsNil)45 expected := Entries{46 &Entry{Host: "127.0.0.1", Port: "2375"},47 &Entry{Host: "127.0.0.2", Port: "2375"},48 &Entry{Host: "2001:db8:0:f101::2", Port: "2375"},49 }50 c.Assert(entries.Equals(expected), check.Equals, true)51 _, err = CreateEntries([]string{"127.0.0.1", "127.0.0.2"})52 c.Assert(err, check.NotNil)53}54func (s *DiscoverySuite) TestContainsEntry(c *check.C) {55 entries, err := CreateEntries([]string{"127.0.0.1:2375", "127.0.0.2:2375", ""})56 c.Assert(err, check.IsNil)57 c.Assert(entries.Contains(&Entry{Host: "127.0.0.1", Port: "2375"}), check.Equals, true)58 c.Assert(entries.Contains(&Entry{Host: "127.0.0.3", Port: "2375"}), check.Equals, false)59}60func (s *DiscoverySuite) TestEntriesEquality(c *check.C) {61 entries := Entries{62 &Entry{Host: "127.0.0.1", Port: "2375"},63 &Entry{Host: "127.0.0.2", Port: "2375"},64 }65 // Same66 c.Assert(entries.Equals(Entries{67 &Entry{Host: "127.0.0.1", Port: "2375"},68 &Entry{Host: "127.0.0.2", Port: "2375"},69 }), check.70 Equals, true)71 // Different size72 c.Assert(entries.Equals(Entries{73 &Entry{Host: "127.0.0.1", Port: "2375"},74 &Entry{Host: "127.0.0.2", Port: "2375"},75 &Entry{Host: "127.0.0.3", Port: "2375"},76 }), check.77 Equals, false)78 // Different content79 c.Assert(entries.Equals(Entries{80 &Entry{Host: "127.0.0.1", Port: "2375"},81 &Entry{Host: "127.0.0.42", Port: "2375"},82 }), check.83 Equals, false)84}85func (s *DiscoverySuite) TestEntriesDiff(c *check.C) {86 entry1 := &Entry{Host: "1.1.1.1", Port: "1111"}87 entry2 := &Entry{Host: "2.2.2.2", Port: "2222"}88 entry3 := &Entry{Host: "3.3.3.3", Port: "3333"}89 entries := Entries{entry1, entry2}90 // No diff91 added, removed := entries.Diff(Entries{entry2, entry1})92 c.Assert(added, check.HasLen, 0)93 c.Assert(removed, check.HasLen, 0)94 // Add95 added, removed = entries.Diff(Entries{entry2, entry3, entry1})96 c.Assert(added, check.HasLen, 1)97 c.Assert(added.Contains(entry3), check.Equals, true)98 c.Assert(removed, check.HasLen, 0)99 // Remove100 added, removed = entries.Diff(Entries{entry2})101 c.Assert(added, check.HasLen, 0)102 c.Assert(removed, check.HasLen, 1)103 c.Assert(removed.Contains(entry1), check.Equals, true)104 // Add and remove105 added, removed = entries.Diff(Entries{entry1, entry3})106 c.Assert(added, check.HasLen, 1)107 c.Assert(added.Contains(entry3), check.Equals, true)108 c.Assert(removed, check.HasLen, 1)109 c.Assert(removed.Contains(entry2), check.Equals, true)110}...

Full Screen

Full Screen

Check

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 addrs, err := net.LookupHost("www.google.com")4 if err != nil {5 fmt.Println("Error:", err.Error())6 }7 for i := 0; i < len(addrs); i++ {8 fmt.Println(addrs[i])9 }10 fmt.Println("Done")11}

Full Screen

Full Screen

Check

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 hosts := []string{4 }5 for _, host := range hosts {6 if Check(host) {7 fmt.Println(host, "is up!")8 } else {9 fmt.Println(host, "is down!")10 }11 }12}13func Check(host string) bool {14 _, err := net.Dial("tcp", host+":80")15 if err != nil {16 }17}

Full Screen

Full Screen

Check

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 hosts := []string{4 }5 c := make(chan string)6 for _, host := range hosts {7 go Check(host, c)8 }9 for i := 0; i < len(hosts); i++ {10 fmt.Println(<-c)11 }12}13func Check(host string, c chan string) {14 if _, err := net.Dial("tcp", host+":80"); err != nil {15 } else {16 }17}

Full Screen

Full Screen

Check

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ips := []net.IPAddr{4 {IP: net.IP{127, 0, 0, 1}},5 {IP: net.IP{8, 8, 8, 8}},6 {IP: net.IP{8, 8, 4, 4}},7 }8 for _, v := range ips {9 fmt.Println(net.CheckIP(v.IP))10 }11}12GoLang net.LookupAddr() Method13func LookupAddr(addr string) (names []string, err error)14import (15func main() {16 ips := []string{

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Syzkaller automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful