Best Venom code snippet using assertions.ShouldNotExist
solrmonitor_test.go
Source:solrmonitor_test.go
1// Copyright 2016 FullStory, Inc.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14//go:build integration15// +build integration16package solrmonitor17import (18 "errors"19 "fmt"20 "runtime"21 "strings"22 "testing"23 "time"24 "github.com/fullstorydev/gosolr/smtestutil"25 "github.com/fullstorydev/gosolr/smutil"26 "github.com/fullstorydev/zk"27)28type testutil struct {29 t *testing.T30 conn *zk.Conn31 root string32 sm *SolrMonitor33 logger *smtestutil.ZkTestLogger34 solrEventListener *SEListener35}36func (tu *testutil) teardown() {37 if err := smutil.DeleteRecursive(tu.conn, tu.root); err != nil {38 tu.t.Error(err)39 }40 if tu.sm != nil {41 tu.sm.Close()42 }43 tu.logger.AssertNoErrors(tu.t)44}45func setup(t *testing.T) (*SolrMonitor, *testutil) {46 t.Parallel()47 pc, _, _, _ := runtime.Caller(1)48 callerFunc := runtime.FuncForPC(pc)49 splits := strings.Split(callerFunc.Name(), "/")50 callerName := splits[len(splits)-1]51 callerName = strings.Replace(callerName, ".", "_", -1)52 if !strings.HasPrefix(callerName, "solrmonitor_Test") {53 t.Fatalf("Unexpected callerName: %s should start with smservice_Test", callerName)54 }55 root := "/" + callerName56 logger := smtestutil.NewZkTestLogger(t)57 watcher := NewZkWatcherMan(logger)58 connOption := func(c *zk.Conn) { c.SetLogger(logger) }59 conn, _, err := zk.Connect([]string{"127.0.0.1:2181"}, time.Second*5, connOption, zk.WithEventCallback(watcher.EventCallback))60 if err != nil {61 t.Fatal(err)62 }63 // Solrmonitor checks the "clusterstate.json" file in the root node it is given.64 // So seed that file.65 _, err = conn.Create(root, nil, 0, zk.WorldACL(zk.PermAll))66 if err != nil && err != zk.ErrNodeExists {67 conn.Close()68 t.Fatal(err)69 }70 _, err = conn.Create(root+"/clusterstate.json", []byte("{}"), 0, zk.WorldACL(zk.PermAll))71 if err != nil && err != zk.ErrNodeExists {72 conn.Close()73 t.Fatal(err)74 }75 l := &SEListener{76 liveNodes: 0,77 queryNodes: 0,78 collections: 0,79 collStateEvents: 0,80 collectionStates: make(map[string]*CollectionState),81 }82 sm, err := NewSolrMonitorWithRoot(conn, watcher, logger, root, l)83 if err != nil {84 conn.Close()85 t.Fatal(err)86 }87 return sm, &testutil{88 t: t,89 conn: conn,90 root: root,91 sm: sm,92 logger: logger,93 solrEventListener: l,94 }95}96// For manual testing, hangs open for a long time.97func disabledTestManual(t *testing.T) {98 _, testutil := setup(t)99 defer testutil.teardown()100 time.Sleep(10 * time.Minute)101}102func TestCollectionChanges(t *testing.T) {103 sm, testutil := setup(t)104 defer testutil.teardown()105 shouldNotExist(t, sm, "c1")106 zkCli := testutil.conn107 zkCli.Create(sm.solrRoot+"/collections", nil, 0, zk.WorldACL(zk.PermAll))108 zkCli.Create(sm.solrRoot+"/live_nodes", nil, 0, zk.WorldACL(zk.PermAll))109 zkCli.Create(sm.solrRoot+"/live_query_nodes", nil, 0, zk.WorldACL(zk.PermAll))110 _, err := zkCli.Create(sm.solrRoot+"/live_nodes/localhost:8983", nil, 0, zk.WorldACL(zk.PermAll))111 if err != nil {112 t.Fatal(err)113 }114 _, err = zkCli.Create(sm.solrRoot+"/live_query_nodes/localhost:8984", nil, 0, zk.WorldACL(zk.PermAll))115 if err != nil {116 t.Fatal(err)117 }118 _, err = zkCli.Create(sm.solrRoot+"/collections/c1", []byte(`{"configName":"_FS5"}`), 0, zk.WorldACL(zk.PermAll))119 if err != nil {120 t.Fatal(err)121 }122 shouldNotExist(t, sm, "c1")123 _, err = zkCli.Create(sm.solrRoot+"/collections/c1/state.json", nil, 0, zk.WorldACL(zk.PermAll))124 if err != nil {125 t.Fatal(err)126 }127 shouldNotExist(t, sm, "c1")128 _, err = zkCli.Set(sm.solrRoot+"/collections/c1/state.json", []byte("{\"c1\":{ \"shards\":{\"shard_1\":{\"replicas\":{\"R1\":{\"core\":\"core1\", \"Base_url\":\"solr\", \"node_name\":\"8984_solr\", \"state\":\"active\", \"leader\":\"false\", \"type\": \"NRT\", \"force_set_state\":\"false\"}}}}}}"), -1)129 if err != nil {130 t.Fatal(err)131 }132 collectionAssertions := func(configName string) func(collectionState *CollectionState) error {133 return func(collectionState *CollectionState) error {134 if collectionState.ConfigName != configName {135 return errors.New(fmt.Sprintf("wrong config name: got %s, expected %s", collectionState.ConfigName, configName))136 }137 shard, _ := collectionState.Shards["shard_1"]138 rep, _ := shard.Replicas["R1"]139 if rep.Leader != "false" {140 return errors.New(fmt.Sprintf("replica is not leader %+v", rep))141 }142 return nil143 }144 }145 shouldExist(t, sm, "c1", collectionAssertions("_FS5"))146 if len(testutil.solrEventListener.collectionStates) != 1 || testutil.solrEventListener.collections != 1 {147 t.Fatalf("Event listener didn't not get event for collection = %d, collectionstate = %d", testutil.solrEventListener.collections, len(testutil.solrEventListener.collectionStates))148 }149 if testutil.solrEventListener.liveNodes != 1 || testutil.solrEventListener.queryNodes != 1 {150 t.Fatalf("Event listener didn't not get event for livenodes = %d, querynodes = %d", testutil.solrEventListener.liveNodes, testutil.solrEventListener.queryNodes)151 }152 // Get a fresh new solr monitor and make sure it starts in the right state.153 w2 := NewZkWatcherMan(testutil.logger)154 connOption := func(c *zk.Conn) { c.SetLogger(testutil.logger) }155 conn2, _, err := zk.Connect([]string{"127.0.0.1:2181"}, time.Second*5, connOption, zk.WithEventCallback(w2.EventCallback))156 if err != nil {157 t.Fatal(err)158 }159 sm2, err := NewSolrMonitorWithRoot(conn2, w2, testutil.logger, testutil.root, nil)160 if err != nil {161 t.Fatal(err)162 }163 defer sm2.Close()164 shouldExist(t, sm2, "c1", collectionAssertions("_FS5"))165 // if the config name changes (not common), we should get the updates166 _, err = zkCli.Set(sm.solrRoot+"/collections/c1", []byte(`{"configName":"_FS6"}`), 0)167 if err != nil {168 t.Fatal(err)169 }170 shouldExist(t, sm2, "c1", collectionAssertions("_FS6"))171 err = smutil.DeleteRecursive(zkCli, sm.solrRoot+"/collections/c1")172 if err != nil {173 t.Fatal(err)174 }175 // which should propagate to the sm instances176 shouldNotExist(t, sm, "c1")177 shouldNotExist(t, sm2, "c1")178}179func TestPRSProtocol(t *testing.T) {180 sm, testutil := setup(t)181 defer testutil.teardown()182 shouldNotExist(t, sm, "c1")183 zkCli := testutil.conn184 zkCli.Create(sm.solrRoot+"/collections", nil, 0, zk.WorldACL(zk.PermAll))185 _, err := zkCli.Create(sm.solrRoot+"/collections/c1", []byte(`{"configName":"_FS4"}`), 0, zk.WorldACL(zk.PermAll))186 if err != nil {187 t.Fatal(err)188 }189 shouldNotExist(t, sm, "c1")190 checkCollectionStateCallback(t, 1, testutil.solrEventListener.collStateEvents+testutil.solrEventListener.collReplicaChangeEvents)191 _, err = zkCli.Create(sm.solrRoot+"/collections/c1/state.json", nil, 0, zk.WorldACL(zk.PermAll))192 if err != nil {193 t.Fatal(err)194 }195 shouldNotExist(t, sm, "c1")196 checkCollectionStateCallback(t, 2, testutil.solrEventListener.collStateEvents+testutil.solrEventListener.collReplicaChangeEvents)197 _, err = zkCli.Set(sm.solrRoot+"/collections/c1/state.json", []byte("{\"c1\":{\"perReplicaState\":\"true\", \"shards\":{\"shard_1\":{\"replicas\":{\"R1\":{\"core\":\"core1\"}}}}}}"), -1)198 if err != nil {199 t.Fatal(err)200 }201 collectionAssertions := func(collectionState *CollectionState) error {202 if collectionState.ConfigName != "_FS4" {203 return errors.New(fmt.Sprintf("wrong config name: got %s, expected %s", collectionState.ConfigName, "_FS4"))204 }205 return nil206 }207 shouldExist(t, sm, "c1", collectionAssertions)208 checkCollectionStateCallback(t, 3, testutil.solrEventListener.collStateEvents+testutil.solrEventListener.collReplicaChangeEvents)209 // 1. adding PRS for replica R1, version 1, state down210 _, err = zkCli.Create(sm.solrRoot+"/collections/c1/state.json/R1:1:D", nil, 0, zk.WorldACL(zk.PermAll))211 if err != nil {212 t.Fatal(err)213 }214 prsShouldExist(t, sm, "c1", "shard_1", "R1", "down", "false", 1)215 checkCollectionStateCallback(t, 4, testutil.solrEventListener.collStateEvents+testutil.solrEventListener.collReplicaChangeEvents)216 // 2. adding PRS for replica R1, version 1 -same, state active => should ignore as same version217 _, err = zkCli.Create(sm.solrRoot+"/collections/c1/state.json/R1:1:R", nil, 0, zk.WorldACL(zk.PermAll))218 if err != nil {219 t.Fatal(err)220 }221 prsShouldExist(t, sm, "c1", "shard_1", "R1", "down", "false", 1)222 checkCollectionStateCallback(t, 5, testutil.solrEventListener.collStateEvents+testutil.solrEventListener.collReplicaChangeEvents)223 // 3. adding PRS for replica R1, version 2, state active224 _, err = zkCli.Create(sm.solrRoot+"/collections/c1/state.json/R1:2:A", nil, 0, zk.WorldACL(zk.PermAll))225 if err != nil {226 t.Fatal(err)227 }228 prsShouldExist(t, sm, "c1", "shard_1", "R1", "active", "false", 2)229 checkCollectionStateCallback(t, 6, testutil.solrEventListener.collStateEvents+testutil.solrEventListener.collReplicaChangeEvents)230 // 4. adding PRS for replica R1, version 3, state active and leader231 _, err = zkCli.Create(sm.solrRoot+"/collections/c1/state.json/R1:3:A:L", nil, 0, zk.WorldACL(zk.PermAll))232 if err != nil {233 t.Fatal(err)234 }235 prsShouldExist(t, sm, "c1", "shard_1", "R1", "active", "true", 3)236 checkCollectionStateCallback(t, 7, testutil.solrEventListener.collStateEvents+testutil.solrEventListener.collReplicaChangeEvents)237 //5. split shard238 _, err = zkCli.Set(sm.solrRoot+"/collections/c1/state.json", []byte("{\"c1\":{\"perReplicaState\":\"true\", \"shards\":{\"shard_1\":{\"replicas\":{\"R1\":{\"core\":\"core1\"}}}, \"shard_1_0\":{\"replicas\":{\"R1_0\":{\"core\":\"core1\"}}}, \"shard_1_1\":{\"replicas\":{\"R1_1\":{\"core\":\"core1\"}}}}}}"), -1)239 if err != nil {240 t.Fatal(err)241 }242 time.Sleep(5000 * time.Millisecond)243 checkCollectionStateCallback(t, 8, testutil.solrEventListener.collStateEvents+testutil.solrEventListener.collReplicaChangeEvents)244 // 6. replica R1_0 should exist245 _, err = zkCli.Create(sm.solrRoot+"/collections/c1/state.json/R1_0:1:A:L", nil, 0, zk.WorldACL(zk.PermAll))246 if err != nil {247 t.Fatal(err)248 }249 prsShouldExist(t, sm, "c1", "shard_1_0", "R1_0", "active", "true", 1)250 checkCollectionStateCallback(t, 9, testutil.solrEventListener.collStateEvents+testutil.solrEventListener.collReplicaChangeEvents)251 // 7. replica R1_1 should exist252 _, err = zkCli.Create(sm.solrRoot+"/collections/c1/state.json/R1_1:1:A:L", nil, 0, zk.WorldACL(zk.PermAll))253 if err != nil {254 t.Fatal(err)255 }256 prsShouldExist(t, sm, "c1", "shard_1_1", "R1_1", "active", "true", 1)257 checkCollectionStateCallback(t, 10, testutil.solrEventListener.collStateEvents+testutil.solrEventListener.collReplicaChangeEvents)258 if testutil.solrEventListener.collStateEvents != 4 || testutil.solrEventListener.collections != 1 {259 t.Fatalf("Event listener didn't not get event for collection = %d, collectionstateEvents = %d", testutil.solrEventListener.collections, testutil.solrEventListener.collStateEvents)260 }261 // and after all of the updates, should still exist with same config name262 shouldExist(t, sm, "c1", collectionAssertions)263}264func checkCollectionStateCallback(t *testing.T, expected int, found int) {265 if expected != found {266 t.Fatalf("listener event is %d, expected %d ", found, expected)267 }268}269//that was meant for cachedState, which we removed as now we need to deserialize the stream as need to know PRS state of collection270func DisabledTestBadStateJson(t *testing.T) {271 sm, testutil := setup(t)272 defer testutil.teardown()273 shouldNotExist(t, sm, "c1")274 zkCli := testutil.conn275 zkCli.Create(sm.solrRoot+"/collections", nil, 0, zk.WorldACL(zk.PermAll))276 _, err := zkCli.Create(sm.solrRoot+"/collections/c1", nil, 0, zk.WorldACL(zk.PermAll))277 if err != nil {278 t.Fatal(err)279 }280 shouldNotExist(t, sm, "c1")281 _, err = zkCli.Create(sm.solrRoot+"/collections/c1/state.json", []byte("asdf"), 0, zk.WorldACL(zk.PermAll))282 if err != nil {283 t.Fatal(err)284 }285 shouldError(t, sm, "c1")286 shouldBecomeEq(t, 1, testutil.logger.GetErrorCount)287 testutil.logger.Clear()288}289type SEListener struct {290 liveNodes int291 queryNodes int292 collections int293 collStateEvents int294 collReplicaChangeEvents int295 collectionStates map[string]*CollectionState296}297func (l *SEListener) SolrLiveNodesChanged(livenodes []string) {298 l.liveNodes = len(livenodes)299}300func (l *SEListener) SolrQueryNodesChanged(querynodes []string) {301 l.queryNodes = len(querynodes)302}303func (l *SEListener) SolrCollectionsChanged(collections []string) {304 l.collections = len(collections)305}306func (l *SEListener) SolrCollectionStateChanged(name string, collectionState *CollectionState) {307 l.collStateEvents++308 l.collectionStates[name] = collectionState309}310func (l *SEListener) SolrCollectionReplicaStatesChanged(name string, replicaStates map[string]*PerReplicaState) {311 l.collReplicaChangeEvents++312}...
venv_test.go
Source:venv_test.go
1// Copyright 2017 The LUCI Authors.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14package venv15import (16 "context"17 "encoding/json"18 "flag"19 "fmt"20 "io/ioutil"21 "os"22 "path/filepath"23 "testing"24 "go.chromium.org/luci/vpython/api/vpython"25 "go.chromium.org/luci/vpython/python"26 "go.chromium.org/luci/common/errors"27 "go.chromium.org/luci/common/logging"28 "go.chromium.org/luci/common/logging/gologger"29 "go.chromium.org/luci/common/sync/parallel"30 "go.chromium.org/luci/common/system/environ"31 "go.chromium.org/luci/common/system/filesystem"32 "go.chromium.org/luci/common/testing/testfs"33 . "github.com/smartystreets/goconvey/convey"34 . "go.chromium.org/luci/common/testing/assertions"35)36var verbose = flag.Bool("test.gologger", false, "Enable Go logging.")37func testContext() context.Context {38 c := context.Background()39 if *verbose {40 c = gologger.StdConfig.Use(c)41 c = logging.SetLevel(c, logging.Debug)42 }43 return c44}45type resolvedInterpreter struct {46 py *python.Interpreter47 version python.Version48}49func resolveFromPath(vers python.Version) *resolvedInterpreter {50 c := testContext()51 py, err := python.Find(c, vers, nil)52 if err != nil {53 return nil54 }55 if err := filesystem.AbsPath(&py.Python); err != nil {56 panic(err)57 }58 ri := resolvedInterpreter{59 py: py,60 }61 if ri.version, err = ri.py.GetVersion(c); err != nil {62 panic(err)63 }64 return &ri65}66var (67 pythonGeneric = resolveFromPath(python.Version{})68 python27 = resolveFromPath(python.Version{Major: 2, Minor: 7, Patch: 0})69 python3 = resolveFromPath(python.Version{Major: 3, Minor: 0, Patch: 0})70)71func TestResolvePythonInterpreter(t *testing.T) {72 t.Parallel()73 // This test is run for each resolved Python interpreter found on the host74 // system.75 testPythonInterpreter := func(c C, ctx context.Context, ri *resolvedInterpreter, vers string) {76 cfg := Config{}77 s := vpython.Spec{78 PythonVersion: vers,79 }80 c.Convey(`Can resolve interpreter version`, func() {81 So(cfg.resolvePythonInterpreter(ctx, &s), ShouldBeNil)82 So(cfg.Python, ShouldEqual, ri.py.Python)83 vers, err := python.ParseVersion(s.PythonVersion)84 So(err, ShouldBeNil)85 So(vers.IsSatisfiedBy(ri.version), ShouldBeTrue)86 })87 c.Convey(`Can resolve Runtime information`, func() {88 var r vpython.Runtime89 err := fillRuntime(ctx, ri.py, &r)90 So(err, ShouldBeNil)91 So(r.Path, ShouldNotEqual, "")92 So(r.Prefix, ShouldNotEqual, "")93 So(r.Hash, ShouldNotEqual, "")94 })95 c.Convey(fmt.Sprintf(`Fails when Python 9999 is requested, but a Python %s interpreter is forced.`, vers), func() {96 cfg.Python = ri.py.Python97 s.PythonVersion = "9999"98 So(cfg.resolvePythonInterpreter(ctx, &s), ShouldErrLike, "doesn't match specification")99 })100 }101 Convey(`Resolving a Python interpreter`, t, func() {102 ctx := testContext()103 // Tests to run if we have Python 2.7 installed.104 if python27 != nil {105 Convey(`When Python 2.7 is requested`, func(c C) {106 testPythonInterpreter(c, ctx, python27, "2.7")107 })108 }109 // Tests to run if we have Python 2.7 and a generic Python installed.110 if pythonGeneric != nil && python27 != nil {111 // Our generic Python resolves to a known version, so we can proceed.112 Convey(`When no Python version is specified, spec resolves to generic.`, func() {113 cfg := Config{}114 s := vpython.Spec{}115 So(cfg.resolvePythonInterpreter(ctx, &s), ShouldBeNil)116 So(cfg.Python, ShouldEqual, pythonGeneric.py.Python)117 vers, err := python.ParseVersion(s.PythonVersion)118 So(err, ShouldBeNil)119 So(vers.IsSatisfiedBy(pythonGeneric.version), ShouldBeTrue)120 })121 }122 // Tests to run if we have Python 3 installed.123 if python3 != nil {124 Convey(`When Python 3 is requested`, func(c C) {125 testPythonInterpreter(c, ctx, python3, "3")126 })127 }128 })129}130type setupCheckManifest struct {131 Interpreter string `json:"interpreter"`132 Pants string `json:"pants"`133 Shirt string `json:"shirt"`134}135func testVirtualEnvWith(t *testing.T, ri *resolvedInterpreter) {136 t.Parallel()137 if ri == nil {138 t.Skipf("No python interpreter found.")139 }140 tl, err := loadTestEnvironment(testContext(), t)141 if err != nil {142 t.Fatalf("could not set up test loader for %q: %s", ri.py.Python, err)143 }144 Convey(`Testing the VirtualEnv`, t, testfs.MustWithTempDir(t, "vpython", func(tdir string) {145 c := testContext()146 // Load the bootstrap wheels for the next part of the test.147 So(tl.ensureWheels(c, t, ri.py, tdir), ShouldBeNil)148 config := Config{149 BaseDir: tdir,150 MaxHashLen: 4,151 SetupEnv: environ.System(),152 Package: vpython.Spec_Package{153 Name: "foo/bar/virtualenv",154 Version: "unresolved",155 },156 Python: ri.py.Python,157 Loader: tl,158 Spec: &vpython.Spec{159 Wheel: []*vpython.Spec_Package{160 {Name: "foo/bar/shirt", Version: "unresolved"},161 {Name: "foo/bar/pants", Version: "unresolved"},162 },163 },164 }165 Convey(`Testing Setup`, func() {166 config.FailIfLocked = true167 err := With(c, config, func(c context.Context, v *Env) error {168 testScriptTarget := python.ScriptTarget{169 Path: filepath.Join(testDataDir, "setup_check.py"),170 }171 checkOut := filepath.Join(tdir, "output.json")172 cmd := v.Interpreter().IsolatedCommand(c, testScriptTarget, "--json-output", checkOut)173 So(cmd.Run(), ShouldBeNil)174 var m setupCheckManifest175 So(loadJSON(checkOut, &m), ShouldBeNil)176 So(m.Interpreter, ShouldStartWith, v.Root)177 So(m.Pants, ShouldStartWith, v.Root)178 So(m.Shirt, ShouldStartWith, v.Root)179 So(v.Environment, ShouldNotBeNil)180 // We should be able to load its environment stamp.181 v.Environment = nil182 So(v.AssertCompleteAndLoad(), ShouldBeNil)183 So(v.Environment, ShouldNotBeNil)184 So(len(v.Environment.Pep425Tag), ShouldBeGreaterThan, 0)185 So(v.Environment.Spec, ShouldNotBeNil)186 So(len(v.Environment.Spec.Wheel), ShouldEqual, len(config.Spec.Wheel))187 So(v.Environment.Spec.Virtualenv, ShouldNotBeNil)188 So(v.Environment.Spec.PythonVersion, ShouldNotEqual, "")189 return nil190 })191 So(err, ShouldBeNil)192 // We should be able to delete it.193 v, err := config.makeEnv(c, nil)194 So(err, ShouldBeNil)195 So(v.Delete(c), ShouldBeNil)196 So(v.Root, shouldNotExist)197 So(v.lockPath, shouldNotExist)198 })199 Convey(`Testing new environment setup race`, func() {200 const workers = 4201 envs := make([]*vpython.Environment, workers)202 err := parallel.FanOutIn(func(taskC chan<- func() error) {203 for i := 0; i < workers; i++ {204 i := i205 taskC <- func() error {206 return With(c, config, func(c context.Context, v *Env) error {207 // Has successfully loaded an Environment.208 envs[i] = v.Environment209 // Can use the Python interpreter.210 if _, err := v.Interpreter().GetVersion(c); err != nil {211 return err212 }213 return nil214 })215 }216 }217 })218 So(err, ShouldBeNil)219 // All Environments must be equal.220 var archetype *vpython.Environment221 for _, env := range envs {222 if archetype == nil {223 archetype = env224 } else {225 So(env, ShouldResembleProto, archetype)226 }227 }228 })229 }))230}231func TestVirtualEnv(t *testing.T) {232 t.Parallel()233 for _, tc := range []struct {234 name string235 ri *resolvedInterpreter236 }{237 {"python27", python27},238 {"python3", python3},239 } {240 tc := tc241 t.Run(fmt.Sprintf(`Testing Virtualenv for: %s`, tc.name), func(t *testing.T) {242 testVirtualEnvWith(t, tc.ri)243 })244 }245}246func loadJSON(path string, dst interface{}) error {247 content, err := ioutil.ReadFile(path)248 if err != nil {249 return errors.Annotate(err, "failed to open file").Err()250 }251 if err := json.Unmarshal(content, dst); err != nil {252 return errors.Annotate(err, "failed to unmarshal JSON").Err()253 }254 return nil255}256func shouldNotExist(actual interface{}, expected ...interface{}) string {257 path := actual.(string)258 switch _, err := os.Stat(path); {259 case err == nil:260 return fmt.Sprintf("Path %q should not exist, but it does.", path)261 case os.IsNotExist(err):262 return ""263 default:264 return fmt.Sprintf("Couldn't check if %q exists: %s", path, err)265 }266}...
set_test.go
Source:set_test.go
1package clap2import (3 "github.com/runaek/clap/pkg/parse"4 "github.com/stretchr/testify/assert"5 "testing"6)7func TestSet_AddFlag(t *testing.T) {8 var testCases = map[string]struct {9 Run func(*Set, *assert.Assertions)10 Exists []Identifier11 DoesNotExist []Identifier12 }{13 "SameNameReturnsErrDuplicate": {14 Run: func(set *Set, a *assert.Assertions) {15 var (16 f1 = NewFlagsP[string](nil, "f1", "f", parse.String{})17 )18 a.NoError(set.AddFlag(f1))19 a.ErrorIs(set.AddFlag(f1), ErrDuplicate)20 },21 Exists: []Identifier{22 Flag("f1"),23 Flag("f"),24 },25 },26 "DuplicateAliasReturnsErrDuplicate": {27 Run: func(set *Set, a *assert.Assertions) {28 var (29 f1 = NewFlagsP[string](nil, "f1", "f", parse.String{})30 f2 = NewFlagP[string](nil, "f2", "f", parse.String{})31 )32 a.NoError(set.AddFlag(f1))33 a.ErrorIs(set.AddFlag(f2), ErrDuplicate)34 //a.True(errors.Is(set.AddFlag(f2), ErrDuplicate))35 },36 Exists: []Identifier{37 Flag("f1"),38 Flag("f"),39 },40 DoesNotExist: []Identifier{41 Flag("f2"),42 },43 },44 }45 for name, tc := range testCases {46 t.Run(name, func(t *testing.T) {47 a := assert.New(t)48 s := NewSet()49 if tc.Run == nil {50 a.Fail("Test has nil Run")51 } else {52 tc.Run(s, a)53 }54 for _, shouldExist := range tc.Exists {55 a.NotNil(s.Get(shouldExist))56 }57 for _, shouldNotExist := range tc.DoesNotExist {58 a.Nil(s.Get(shouldNotExist))59 }60 })61 }62}63func TestSet_AddKeyValue(t *testing.T) {64 var testCases = map[string]struct {65 Run func(*Set, *assert.Assertions)66 Exists []Identifier67 DoesNotExist []Identifier68 }{69 "SameNameReturnsErrDuplicate": {70 Run: func(set *Set, a *assert.Assertions) {71 var (72 k1 = NewKeyValue[string](nil, "key1", parse.String{}, WithAlias("k"))73 )74 a.NoError(set.AddKeyValue(k1))75 a.ErrorIs(set.AddKeyValue(k1), ErrDuplicate)76 //a.True(errors.Is(set.AddKeyValue(k1), ErrDuplicate))77 },78 Exists: []Identifier{79 Key("key1"),80 Key("k"),81 },82 },83 "DuplicateAliasReturnsErrDuplicate": {84 Run: func(set *Set, a *assert.Assertions) {85 var (86 k1 = NewKeyValue[string](nil, "key1", parse.String{}, WithAlias("k"))87 k2 = NewKeyValue[string](nil, "key2", parse.String{}, WithAlias("k"))88 )89 a.NoError(set.AddKeyValue(k1))90 a.ErrorIs(set.AddKeyValue(k2), ErrDuplicate)91 //a.True(errors.Is(set.AddKeyValue(k2), ErrDuplicate))92 },93 Exists: []Identifier{94 Key("key1"),95 Key("k"),96 },97 DoesNotExist: []Identifier{98 Key("key2"),99 },100 },101 }102 for name, tc := range testCases {103 t.Run(name, func(t *testing.T) {104 a := assert.New(t)105 s := NewSet()106 if tc.Run == nil {107 a.Fail("Test has nil Run")108 } else {109 tc.Run(s, a)110 }111 for _, shouldExist := range tc.Exists {112 a.NotNil(s.Get(shouldExist))113 }114 for _, shouldNotExist := range tc.DoesNotExist {115 a.Nil(s.Get(shouldNotExist))116 }117 })118 }119}120func TestSet_AddPosition(t *testing.T) {121 var testCases = map[string]struct {122 Run func(*Set, *assert.Assertions)123 Exists []Identifier124 DoesNotExist []Identifier125 }{126 "DuplicateIndexReturnsErr": {127 Run: func(set *Set, a *assert.Assertions) {128 var (129 p1 = NewPosition[string](nil, 1, parse.String{})130 p2 = NewPosition[string](nil, 2, parse.String{})131 p22 = NewPosition[string](nil, 2, parse.String{})132 )133 a.NoError(set.AddPosition(p1))134 a.NoError(set.AddPosition(p2))135 a.ErrorIs(set.AddPosition(p22), ErrDuplicate)136 //a.True(errors.Is(set.AddPosition(p22), ErrDuplicate))137 },138 Exists: []Identifier{139 Position(1),140 Position(2),141 },142 },143 "PositionAfterVariadicReturnsErr": {144 Run: func(set *Set, a *assert.Assertions) {145 var (146 p1 = NewPosition[string](nil, 1, parse.String{})147 p2 = NewPosition[string](nil, 2, parse.String{})148 p3 = NewPositions[string](nil, 3, parse.String{})149 p4 = NewPosition[string](nil, 4, parse.String{})150 )151 a.NoError(set.AddPosition(p1))152 a.NoError(set.AddPosition(p2))153 a.NoError(set.AddPosition(p3))154 a.ErrorIs(set.AddPosition(p4), ErrInvalidIndex)155 //e := set.AddPosition(p4)156 //a.Truef(errors.Is(e, ErrInvalidIndex), "unexpected error: want %s but got %s", ErrInvalidIndex, e)157 },158 Exists: []Identifier{159 Position(1),160 Position(2),161 Position(3),162 },163 },164 "RequiredCannotComeAfterOptional": {165 Run: func(set *Set, a *assert.Assertions) {166 var (167 p1 = NewPosition[string](nil, 1, parse.String{})168 p2 = NewPosition[string](nil, 2, parse.String{}, AsRequired())169 )170 a.NoError(set.AddPosition(p1))171 e := set.AddPosition(p2)172 a.ErrorIs(e, ErrInvalidIndex)173 },174 Exists: []Identifier{175 Position(1),176 },177 },178 }179 for name, tc := range testCases {180 t.Run(name, func(t *testing.T) {181 a := assert.New(t)182 s := NewSet()183 if tc.Run == nil {184 a.Fail("Test has nil Run")185 } else {186 tc.Run(s, a)187 }188 for _, shouldExist := range tc.Exists {189 a.NotNil(s.Get(shouldExist))190 }191 for _, shouldNotExist := range tc.DoesNotExist {192 a.Nil(s.Get(shouldNotExist))193 }194 })195 }196}197func TestSet_AddPipe(t *testing.T) {198 var testCases = map[string]struct {199 Run func(*Set, *assert.Assertions)200 Exists []Identifier201 DoesNotExist []Identifier202 }{203 "OnlyOnePipe": {204 Run: func(set *Set, a *assert.Assertions) {205 var (206 p1 = NewPipeArg[string](nil, parse.String{}, nil, nil)207 p2 = NewPipeArg[string](nil, parse.String{}, nil, nil)208 )209 a.NoError(set.AddPipe(p1))210 a.ErrorIs(set.AddPipe(p2), ErrPipeExists)211 //e := set.AddPipe(p2)212 //a.Truef(errors.Is(e, ErrPipeExists), "unexpected error: want %s but got %s", ErrPipeExists, e)213 },214 Exists: []Identifier{215 Pipe(""),216 },217 },218 }219 for name, tc := range testCases {220 t.Run(name, func(t *testing.T) {221 a := assert.New(t)222 s := NewSet()223 if tc.Run == nil {224 a.Fail("Test has nil Run")225 } else {226 tc.Run(s, a)227 }228 for _, shouldExist := range tc.Exists {229 a.NotNil(s.Get(shouldExist))230 }231 for _, shouldNotExist := range tc.DoesNotExist {232 a.Nil(s.Get(shouldNotExist))233 }234 })235 }236}...
ShouldNotExist
Using AI Code Generation
1import (2func TestShouldNotExist(t *testing.T) {3 RegisterFailHandler(Fail)4 RunSpecs(t, "ShouldNotExist Suite")5}6var _ = Describe("ShouldNotExist", func() {7 Context("To check whether a file exists or not", func() {8 It("Should not exist", func() {9 Expect("/home/satish/Downloads/abc.txt").ShouldNot(BeAnExistingFile())10 })11 })12})13import (14func TestShouldExist(t *testing.T) {15 RegisterFailHandler(Fail)16 RunSpecs(t, "ShouldExist Suite")17}18var _ = Describe("ShouldExist", func() {19 Context("To check whether a file exists or not", func() {20 It("Should exist", func() {21 Expect("/home/satish/Downloads/abc.txt").Should(BeAnExistingFile())22 })23 })24})25import (26func TestShouldBeAnExistingDir(t *testing.T) {27 RegisterFailHandler(Fail)28 RunSpecs(t, "ShouldBeAnExistingDir Suite")29}30var _ = Describe("ShouldBeAnExistingDir", func() {31 Context("To check whether a directory exists or not", func() {32 It("Should exist", func() {33 Expect("/home/satish/Downloads").Should(BeAnExistingDir())34 })35 })36})37import (38func TestShouldBeAnExistingDir(t *testing.T) {39 RegisterFailHandler(Fail)40 RunSpecs(t, "ShouldBeAnExistingDir Suite")41}42var _ = Describe("ShouldBeAnExistingDir",
ShouldNotExist
Using AI Code Generation
1import (2func TestShouldNotExist(t *testing.T) {3 assert := assert.New(t)4 file, err := os.Create("test.txt")5 assert.NoError(err)6 file.Close()7 assert.FileExists("test.txt")8 assert.FileNotExists("test.txt")9}10import (11func TestShouldBeTrue(t *testing.T) {12 assert := assert.New(t)13 assert.True(true)14}15import (16func TestShouldBeFalse(t *testing.T) {17 assert := assert.New(t)18 assert.False(false)19}20import (21func TestShouldBeEmpty(t *testing.T) {22 assert := assert.New(t)23 assert.Empty("")24}25import (26func TestShouldBeNil(t *testing.T) {27 assert := assert.New(t)28 assert.Nil(nil)29}30import (31func TestShouldBeZeroValue(t *testing.T) {32 assert := assert.New(t)33 assert.Zero(i)34}35import (36func TestShouldBeBetween(t *testing.T) {37 assert := assert.New(t)38 assert.InDelta(5, 6, 1)39}40import (41func TestShouldBeBetween(t *testing.T) {42 assert := assert.New(t
ShouldNotExist
Using AI Code Generation
1import (2func TestFileShouldNotExist(t *testing.T) {3 assert := assert.New(t)4 _, err := os.Stat("test.txt")5 assert.True(os.IsNotExist(err), "File should not exist.")6}7func main() {8 fmt.Println("File should not exist")9}
ShouldNotExist
Using AI Code Generation
1import (2func TestFileDoesNotExist(t *testing.T) {3 assert := assert.New(t)4 assert.FileExists("test.txt", "File should exist")5 assert.FileExists("test1.txt", "File should exist")6 assert.FileExists("test2.txt", "File should exist")7 assert.FileExists("test3.txt", "File should exist")8 assert.FileExists("test4.txt", "File should exist")9 assert.FileExists("test5.txt", "File should exist")10 assert.FileExists("test6.txt", "File should exist")11 assert.FileExists("test7.txt", "File should exist")12 assert.FileExists("test8.txt", "File should exist")13 assert.FileExists("test9.txt", "File should exist")14 assert.FileExists("test10.txt", "File should exist")15 assert.FileExists("test11.txt", "File should exist")16 assert.FileExists("test12.txt", "File should exist")17 assert.FileExists("test13.txt", "File should exist")18 assert.FileExists("test14.txt", "File should exist")19 assert.FileExists("test15.txt", "File should exist")20 assert.FileExists("test16.txt", "File should exist")21 assert.FileExists("test17.txt", "File should exist")22 assert.FileExists("test18.txt", "File should exist")23 assert.FileExists("test19.txt", "File should exist")24 assert.FileExists("test20.txt", "File should exist")25 assert.FileExists("test21.txt", "File should exist")26 assert.FileExists("test22.txt", "File should exist")27 assert.FileExists("test23.txt", "File should exist")28 assert.FileExists("test24.txt", "File should exist")29 assert.FileExists("test25.txt", "File should exist")30 assert.FileExists("test26.txt", "File should exist")31 assert.FileExists("test27.txt", "File should exist")32 assert.FileExists("test28.txt", "File should exist")33 assert.FileExists("test29.txt", "File should exist")34 assert.FileExists("test30.txt", "File should exist")35 assert.FileExists("test31.txt", "File should exist")36 assert.FileExists("test32.txt", "File should exist")37 assert.FileExists("test33.txt", "File should exist")38 assert.FileExists("test34.txt", "File should exist")39 assert.FileExists("test35.txt",
ShouldNotExist
Using AI Code Generation
1import (2func TestShouldNotExist(t *testing.T) {3 assert := assert.New(t)4 assert.ShouldNotExist("a", "b", "c")5}6--- FAIL: TestShouldNotExist (0.00s)7testing.tRunner.func1(0xc4200a8000)8panic(0x4c3e00, 0xc42000e1e0)9github.com/stretchr/testify/assert.(*Assertions).ShouldNotExist(0xc42000e1b0, 0xc42000e1c0, 0x3, 0x3)10main.TestShouldNotExist(0xc4200a8000)11testing.tRunner(0xc4200a8000, 0x4e9f48)12created by testing.(*T).Run13import (14func TestShouldNotBeNil(t *testing.T) {15 assert := assert.New(t)16 assert.ShouldNotBeNil("a", "b", "c")17}18--- FAIL: TestShouldNotBeNil (0.00s)19testing.tRunner.func1(0xc4200a8000)20panic(0x4c3e00, 0
ShouldNotExist
Using AI Code Generation
1import (2func TestShouldNotExist(t *testing.T) {3assert := assert.New(t)4assert.ShouldNotExist(1, "message %s", "formatted")5}6import (7func TestShouldNotBeNil(t *testing.T) {8assert := assert.New(t)9assert.ShouldNotBeNil(1, "message %s", "formatted")10}11import (12func TestShouldNotBeZeroValue(t *testing.T) {13assert := assert.New(t)14assert.ShouldNotBeZeroValue(1, "message %s", "formatted")15}16import (17func TestShouldNotBeEmpty(t *testing.T) {18assert := assert.New(t)19assert.ShouldNotBeEmpty(1, "message %s", "formatted")20}21import (22func TestShouldNotBeFalse(t *testing.T) {23assert := assert.New(t)24assert.ShouldNotBeFalse(1, "message %s", "formatted")25}26import (27func TestShouldNotBeTrue(t *testing.T) {28assert := assert.New(t)29assert.ShouldNotBeTrue(1, "message %s", "formatted")30}31import (32func TestShouldNotBeTypeOf(t *testing.T) {33assert := assert.New(t)34assert.ShouldNotBeTypeOf(1, "message %s", "formatted")35}36import (37func TestShouldNotBeSameTypeAs(t *testing.T) {38assert := assert.New(t)39assert.ShouldNotBeSameTypeAs(1, "message %s", "formatted")40}
ShouldNotExist
Using AI Code Generation
1func TestShouldNotExist(t *testing.T) {2 assertion := assert.New(t)3 assertion.ShouldNotExist("C:/Users/abc/Downloads/sample.txt")4}5func TestShouldNotExist(t *testing.T) {6 assertion := assert.New(t)7 assertion.ShouldNotExist("C:/Users/abc/Downloads/sample1.txt")8}9--- FAIL: TestShouldNotExist (0.00s)10func TestShouldNotExist(t *testing.T) {11 assertion := assert.New(t)12 assertion.ShouldNotExist("C:/Users/abc/Downloads")13}14--- FAIL: TestShouldNotExist (0.00s)15func TestShouldNotExist(t *testing.T) {16 assertion := assert.New(t)17 assertion.ShouldNotExist("C:/Users/abc/Downloads/sample.txt")18}19--- FAIL: TestShouldNotExist (0.00s)
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!