Best Venom code snippet using dbfixtures.loadFixtures
server_test.go
Source:server_test.go
...67 // Discard logging from the application to focus on test logs68 // NOTE: ConsoleLog MUST be false otherwise this will be overriden69 logger.Discard()70 // Load the fixtures then regenerate the test database if requested or required.71 require.NoError(s.loadFixtures())72 if _, err := os.Stat(dbtgz); *update || os.IsNotExist(err) {73 require.NoError(s.generateDB())74 }75 // Create the initial configuration, database fixture, and servers for the tests76 require.NoError(s.setupConfig())77 require.NoError(s.extractDB())78 require.NoError(s.setupServers())79 require.NoError(s.setupRemoteTrtl())80}81func (s *trtlTestSuite) TearDownSuite() {82 require := s.Require()83 require.NoError(s.cleanup())84 logger.ResetLogger()85}86//===========================================================================87// Server Tests88//===========================================================================89func TestTrtl(t *testing.T) {90 suite.Run(t, new(trtlTestSuite))91}92func (s *trtlTestSuite) TestMaintenance() {93 // Becasue we're modifying the configuration, ensure we reset the test environment94 defer s.reset()95 require := s.Require()96 s.conf.Maintenance = true97 server, err := trtl.New(*s.conf)98 require.NotEmpty(server, "no maintenance mode server was returned")99 require.NoError(err, "starting the server in maintenance mode caused an error")100 require.Nil(server.GetDB(), "maintenance mode database was not nil")101}102//===========================================================================103// Test Assertions104//===========================================================================105// StatusError is a helper assertion function that checks a gRPC status error106func (s *trtlTestSuite) StatusError(err error, code codes.Code, theError string) {107 require := s.Require()108 require.Error(err, "no status error returned")109 var serr *status.Status110 serr, ok := status.FromError(err)111 require.True(ok, "error is not a grpc status error")112 require.Equal(code, serr.Code(), "status code does not match")113 require.Equal(theError, serr.Message(), "status error message does not match")114}115// EqualMeta is a helper assertion function that checks if the actual metadata matches116// expectations about what the version should be. This helper function relies on some117// test fixture information to minimize what test users must supply.118func (s *trtlTestSuite) EqualMeta(expectedKey []byte, expectedNamespace string, expectedVersion, expectedParent *pb.Version, actualMeta *pb.Meta) {119 require := s.Require()120 require.NotNil(actualMeta, "cannot compare actual meta to expectations since actual meta is nil")121 expectedMeta := &pb.Meta{122 Key: expectedKey,123 Namespace: expectedNamespace,124 Region: s.conf.Replica.Region,125 Owner: fmt.Sprintf("%d:%s", s.conf.Replica.PID, s.conf.Replica.Name),126 Version: expectedVersion,127 Parent: expectedParent,128 }129 // Protocol buffer sanity check, this protects us from the case where the protocol buffers130 // have changed but the tests haven't been updated.131 if proto.Equal(actualMeta, expectedMeta) {132 // If the protocol buffers are equal, then we expect that everything is ok133 return134 }135 // At this point it's up to us to determine what the difference is between the versions136 require.Equal(expectedMeta.Key, actualMeta.Key, "meta keys do not match")137 require.Equal(expectedMeta.Namespace, actualMeta.Namespace, "meta namespace does not match")138 require.Equal(expectedMeta.Region, actualMeta.Region, "meta regions do not match")139 require.Equal(expectedMeta.Owner, actualMeta.Owner, "meta owners do not match")140 s.EqualVersion(expectedMeta.Version, actualMeta.Version, "version")141 s.EqualVersion(expectedMeta.Parent, actualMeta.Parent, "parent")142 // Could not determine the difference in the protocol buffers, so error generically143 require.True(proto.Equal(actualMeta, expectedMeta), "actual and expected protocol buffer metadata does not match")144}145// EqualVersion compares to Versions to see if they are the same146func (s *trtlTestSuite) EqualVersion(expectedVersion, actualVersion *pb.Version, versionType string) {147 require := s.Require()148 if expectedVersion == nil {149 require.Nil(actualVersion, "expected %s is nil but actual %s is not", versionType, versionType)150 return151 }152 require.Equal(expectedVersion.Pid, actualVersion.Pid, "expected %s PID does not match actual %s PID", versionType, versionType)153 require.Equal(expectedVersion.Version, actualVersion.Version, "expected %s scalar does not match actual %s scalar", versionType, versionType)154 require.Equal(expectedVersion.Region, actualVersion.Region, "expected %s region does not match actual %s region", versionType, versionType)155}156//===========================================================================157// Test setup helpers158//===========================================================================159// Creates a valid config for the tests so long as the current config is empty160func (s *trtlTestSuite) setupConfig() (err error) {161 if s.conf != nil || s.tmpdb != "" {162 return errors.New("cannot create configuration, run test suite cleanup first")163 }164 // Create a tmp directory for the database165 if s.tmpdb, err = ioutil.TempDir("testdata", "trtldb-*"); err != nil {166 return fmt.Errorf("could not create tmpdb: %s", err)167 }168 // Create the configuration without loading it from the environment169 conf := mock.Config()170 conf.Database.URL = fmt.Sprintf("leveldb:///%s", s.tmpdb)171 // Mark as processed since the config wasn't loaded from the environment172 if conf, err = conf.Mark(); err != nil {173 return fmt.Errorf("could not validate test configuration: %s", err)174 }175 // Set the configuration as a pointer so individual tests can modify the config as needed176 s.conf = &conf177 return nil178}179// creates and runs all of the trtl services in preparation for testing180func (s *trtlTestSuite) setupServers() (err error) {181 if s.conf == nil {182 return errors.New("no configuration, run s.setupConfig first")183 }184 // Create the trtl server185 if s.trtl, err = trtl.New(*s.conf); err != nil {186 return fmt.Errorf("could not create trtl service: %s", err)187 }188 // Create a bufconn listener(s) so that there are no actual network requests189 s.grpc = bufconn.New(bufSize, "")190 // Run the test server without signals, background routines or maintenance mode checks191 // TODO: do we need to check if there was an error when starting run?192 go s.trtl.Run(s.grpc.Listener)193 return nil194}195// creates and serves the RemoteTrtl server over bufconn using TLS credentials.196// Connections to trtl are always over mTLS, so the purpose of the remote trtl server197// is to have a peer that the tests can establish realistic connections to. In order to198// do this, the testdata directory contains two self-signed certificates generated by199// the certs CLI command. It doesn't matter which certificate the remote trtl server200// uses, but tests should use the opposite one to be able to connect over mTLS to the201// remote.202func (s *trtlTestSuite) setupRemoteTrtl() (err error) {203 // Create the server TLS configuration from the fixture204 var tls *tls.Config205 conf := config.MTLSConfig{206 ChainPath: serverCerts,207 CertPath: serverCerts,208 }209 if tls, err = conf.ParseTLSConfig(); err != nil {210 return fmt.Errorf("could not parse tls config: %s", err)211 }212 // Create the grpc server options with TLS213 opts := make([]grpc.ServerOption, 0)214 opts = append(opts, grpc.Creds(credentials.NewTLS(tls)))215 // Create the remote peer216 s.remote = mock.New(bufconn.New(bufSize, serverTarget), opts...)217 return nil218}219//===========================================================================220// Test cleanup helpers221//===========================================================================222// cleanup the current temporary directory, configuration, and running services.223func (s *trtlTestSuite) cleanup() (err error) {224 // Shutdown the trtl server if it is running225 // This should shutdown all the running services and close the database226 // Note that Shutdown should be graceful and not shutdown anything not running.227 if s.trtl != nil {228 if err = s.trtl.Shutdown(); err != nil {229 return err230 }231 }232 // Shutdown the gRPC connection if it's running233 if s.grpc != nil {234 s.grpc.Release()235 }236 // Cleanup the tmpdb and delete any stray files237 if s.tmpdb != "" {238 os.RemoveAll(s.tmpdb)239 }240 // Cleanup the remote trtl peer241 if s.remote != nil {242 s.remote.Shutdown()243 }244 // Reset all of the test suite variables245 s.tmpdb = ""246 s.conf = nil247 s.grpc = nil248 s.trtl = nil249 s.remote = nil250 return nil251}252// reset the test environment, refreshing the honu database fixture and all of the253// services. This is useful if the test makes changes to the database, though it is254// somewhat heavyweight since it blows away the prior configuration, running servers,255// and open database connection.256func (s *trtlTestSuite) reset() {257 require := s.Require()258 // Reset the previous environment259 s.resetEnvironment()260 // Run the trtl server on the new configuration261 require.NoError(s.setupServers(), "could not reset servers")262 // Run the remote trtl peer263 require.NoError(s.setupRemoteTrtl(), "could not reset remote trtl")264}265// shutdown the trtl servers and reset the configuration and fixtures266func (s *trtlTestSuite) resetEnvironment() {267 require := s.Require()268 // Cleanup previous configuration and shutdown servers, deleting the tmp database.269 require.NoError(s.cleanup(), "could not cleanup before reset")270 // Setup a new configuration and tmpdb271 require.NoError(s.setupConfig(), "could not reset configuration")272 // Extract the honu db fixture into tmpdb273 require.NoError(s.extractDB(), "could not reset db")274}275//===========================================================================276// Test fixtures management277//===========================================================================278// loads client credentials from disk and returns grpc.DialOptions to use for TLS279// client connections.280func (s *trtlTestSuite) loadClientCredentials() (opts []grpc.DialOption, err error) {281 opts = make([]grpc.DialOption, 0)282 // Load the client credentials from the fixtures283 var sz *trust.Serializer284 if sz, err = trust.NewSerializer(false); err != nil {285 return nil, err286 }287 var pool trust.ProviderPool288 if pool, err = sz.ReadPoolFile(clientCerts); err != nil {289 return nil, err290 }291 var provider *trust.Provider292 if provider, err = sz.ReadFile(clientCerts); err != nil {293 return nil, err294 }295 // Create the TLS configuration from the client credentials296 var cert tls.Certificate297 if cert, err = provider.GetKeyPair(); err != nil {298 return nil, err299 }300 var certPool *x509.CertPool301 if certPool, err = pool.GetCertPool(false); err != nil {302 return nil, err303 }304 var u *url.URL305 if u, err = url.Parse(serverTarget); err != nil {306 return nil, err307 }308 conf := &tls.Config{309 ServerName: u.Host,310 Certificates: []tls.Certificate{cert},311 RootCAs: certPool,312 }313 opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(conf)))314 return opts, nil315}316// loads the test fixtures from a JSON file and stores them in the dbFixtures map -317// these fixtures are used both for generating the test database and for making318// comparative assertions in test code.319func (s *trtlTestSuite) loadFixtures() (err error) {320 var fixtures []byte321 if fixtures, err = ioutil.ReadFile("testdata/db.json"); err != nil {322 return fmt.Errorf("could not read fixtures at testdata/db.json: %s", err)323 }324 if err = json.Unmarshal(fixtures, &dbFixtures); err != nil {325 return fmt.Errorf("could not unmarshal fixtures at testdata/db.json: %s", err)326 }327 return nil328}329// extract honu database from generated fixtures - the honu db fixture is interacted330// with directly by the code and we expect that the data in the honu db fixture mates331// the in-memory fixtures defined by dbFixtures. If there is a mismatch, delete332// testdata/db.tgz or run the tests with the -update flag to regenerate them.333func (s *trtlTestSuite) extractDB() (err error) {334 if s.tmpdb == "" {335 return errors.New("no temporary database, run s.setupConfig first")336 }337 // Always extract the test database to a temporary directory.338 if _, err = utils.ExtractGzip(dbtgz, s.tmpdb, true); err != nil {339 return fmt.Errorf("unable to extract honu db fixture: %s", err)340 }341 return nil342}343// generates an updated database and compresses it to a gzip file.344// NOTE: loadFixtures must have been called before this method.345func (s *trtlTestSuite) generateDB() (err error) {346 // Create a new and temporary db to write the fixtures into347 if err = s.setupConfig(); err != nil {348 return err349 }350 // Ensure we cleanup so that subsequent tests can generate tmpdb directories351 defer s.cleanup()352 // Open a honu database, all fixtures will be written by Honu, which means that Honu353 // will be performing all version management, we expect that everything is at the354 // first version when the fixtures database is created.355 var db *honu.DB356 if db, err = honu.Open(s.conf.Database.URL, s.conf.GetHonuConfig()); err != nil {357 return fmt.Errorf("could not open tmp honu database in %s: %s", s.tmpdb, err)358 }...
dbfixtures.go
Source:dbfixtures.go
...83 }84 venom.Debug(ctx, "applied %d migrations\n", n)85 }86 // Load fixtures in the databases.87 if err = loadFixtures(ctx, db, e.Files, e.Folder, getDialect(e.Database, e.SkipResetSequences), workdir); err != nil {88 return nil, err89 }90 r := Result{Executor: e}91 return r, nil92}93// ZeroValueResult return an empty implementation of this executor result94func (Executor) ZeroValueResult() interface{} {95 return Result{}96}97// GetDefaultAssertions return the default assertions of the executor.98func (e Executor) GetDefaultAssertions() venom.StepAssertions {99 return venom.StepAssertions{Assertions: []venom.Assertion{}}100}101// loadFixtures loads the fixtures in the database.102// It gives priority to the fixtures files found in folder,103// and switch to the list of files if no folder was specified.104func loadFixtures(ctx context.Context, db *sql.DB, files []string, folder string, dialect func(*fixtures.Loader) error, workdir string) error {105 if folder != "" {106 venom.Debug(ctx, "loading fixtures from folder %s\n", path.Join(workdir, folder))107 loader, err := fixtures.New(108 // By default the package refuse to load if the database109 // does not contains "test" to avoid wiping a production db.110 fixtures.DangerousSkipTestDatabaseCheck(),111 fixtures.Database(db),112 fixtures.Directory(path.Join(workdir, folder)),113 dialect)114 if err != nil {115 return errors.Wrapf(err, "failed to create folder loader")116 }117 if err = loader.Load(); err != nil {118 return errors.Wrapf(err, "failed to load fixtures from folder %q", path.Join(workdir, folder))...
repository_test.go
Source:repository_test.go
...83 sort.Strings(resultChirps[0].Tags)84 assert.Equal(s.T(), reflect.DeepEqual(resultChirps[0].Tags, pq.StringArray{"tag1", "tag2"}), true, "chirp should contain correct tags")85}86func (s *Suite) Test_repository_GetChirps() {87 s.loadFixtures()88 resultChirps, err := s.repository.GetChirps([]string{"tag1"})89 require.NoError(s.T(), err)90 assert.Equal(s.T(), len(resultChirps), 1, "there should be one chirp")91 assert.Equal(s.T(), resultChirps[0].Message, "test_message", "chirp should contain correct message")92 assert.Equal(s.T(), resultChirps[0].Author, "test_user", "chirp should contain correct author")93 sort.Strings(resultChirps[0].Tags)94 assert.Equal(s.T(), reflect.DeepEqual(resultChirps[0].Tags, pq.StringArray{"tag1", "tag2"}), true, "chirp should contain correct tags")95}96func (s *Suite) Test_repository_CountChirps() {97 s.loadFixtures()98 chirpsCount, err := s.repository.CountChirps("2016-01-01", "2016-01-02", []string{"tag1"})99 require.NoError(s.T(), err)100 assert.Equal(s.T(), chirpsCount, 1, "there should be one chirp")101}102func (s *Suite) clearDB() {103 tx := s.DB.MustBegin()104 tx.MustExec(`DELETE FROM chirps_tags;`)105 tx.MustExec(`DELETE FROM chirps;`)106 tx.MustExec(`DELETE FROM tags;`)107 tx.MustExec(`DELETE FROM users;`)108 if err := tx.Commit(); err != nil {109 log.Fatal(err)110 }111}112func (s *Suite) loadFixtures() {113 err := s.fixtures.Load()114 if err != nil {115 log.Fatal(errors.Wrap(err, "could not load fixtures"))116 }117}...
loadFixtures
Using AI Code Generation
1import (2type ApiTestSuite struct {3}4func (s *ApiTestSuite) SetupSuite() {5 s.server = httptest.NewServer(server.NewRouter())6}7func (s *ApiTestSuite) TearDownSuite() {8 s.server.Close()9}10func (s *ApiTestSuite) TestGetUsers() {11 fixtures := tests.LoadFixtures(s.T(), "users")12 defer fixtures.Clean()13 Body(`[14 {
loadFixtures
Using AI Code Generation
1dbfixtures.loadFixtures('fixtures', function (err) {2 if (err) {3 console.log(err);4 } else {5 console.log('Fixtures loaded');6 }7});8dbfixtures.loadFixtures('fixtures', function (err) {9 if (err) {10 console.log(err);11 } else {12 console.log('Fixtures loaded');13 }14});15dbfixtures.loadFixtures('fixtures', function (err) {16 if (err) {17 console.log(err);18 } else {19 console.log('Fixtures loaded');20 }21});22dbfixtures.loadFixtures('fixtures', function (err) {23 if (err) {24 console.log(err);25 } else {26 console.log('Fixtures loaded');27 }28});29dbfixtures.loadFixtures('fixtures', function (err) {30 if (err) {31 console.log(err);32 } else {33 console.log('Fixtures loaded');34 }35});36dbfixtures.loadFixtures('fixtures', function (err) {37 if (err) {38 console.log(err);39 } else {40 console.log('Fixtures loaded');41 }42});43dbfixtures.loadFixtures('fixtures', function (err) {44 if (err) {45 console.log(err);46 } else {47 console.log('Fixtures loaded');48 }49});50dbfixtures.loadFixtures('fixtures', function (err) {51 if (err) {52 console.log(err);53 } else {54 console.log('Fixtures loaded');55 }56});57dbfixtures.loadFixtures('fixtures', function (err) {58 if (err) {59 console.log(err);60 }
loadFixtures
Using AI Code Generation
1import (2func TestLoadFixtures(t *testing.T) {3 db := NewDB()4 db.LoadFixtures()5 user := db.GetUserById(1)6 assert.Equal(t, "John", user.Name)7 assert.Equal(t, "Doe", user.Surname)8 assert.Equal(t, "
loadFixtures
Using AI Code Generation
1func main() {2 dbFixtures := dbfixtures.NewDbFixtures(db)3 err := dbFixtures.LoadFixtures("path/to/fixtures")4 if err != nil {5 log.Fatal(err)6 }7}8func main() {9 dbFixtures := dbfixtures.NewDbFixtures(db)10 err := dbFixtures.LoadFixtures("path/to/fixtures")11 if err != nil {12 log.Fatal(err)13 }14}15func main() {16 dbFixtures := dbfixtures.NewDbFixtures(db)17 err := dbFixtures.LoadFixtures("path/to/fixtures")18 if err != nil {19 log.Fatal(err)20 }21}22func main() {23 dbFixtures := dbfixtures.NewDbFixtures(db)24 err := dbFixtures.LoadFixtures("path/to/fixtures")25 if err != nil {26 log.Fatal(err)27 }28}29func main() {30 dbFixtures := dbfixtures.NewDbFixtures(db)31 err := dbFixtures.LoadFixtures("path/to/fixtures")32 if err != nil {33 log.Fatal(err)34 }35}36func main() {37 dbFixtures := dbfixtures.NewDbFixtures(db)38 err := dbFixtures.LoadFixtures("path/to/fixtures")39 if err != nil {40 log.Fatal(err)41 }42}43func main() {44 dbFixtures := dbfixtures.NewDbFixtures(db)45 err := dbFixtures.LoadFixtures("path/to/fixtures")46 if err != nil {47 log.Fatal(err)48 }49}50func main() {51 dbFixtures := dbfixtures.NewDbFixtures(db)52 err := dbFixtures.LoadFixtures("path/to/fixtures")53 if err != nil {54 log.Fatal(err)55 }56}
loadFixtures
Using AI Code Generation
1func main() {2 dbfixtures.LoadFixtures("fixtures", "users")3 dbfixtures.LoadFixtures("fixtures", "posts")4 dbfixtures.LoadFixtures("fixtures", "comments")5}6func main() {7 dbfixtures.LoadFixtures("fixtures", "users")8 dbfixtures.LoadFixtures("fixtures", "posts")9 dbfixtures.LoadFixtures("fixtures", "comments")10}11func main() {12 dbfixtures.LoadFixtures("fixtures", "users")13 dbfixtures.LoadFixtures("fixtures", "posts")14 dbfixtures.LoadFixtures("fixtures", "comments")15}16func main() {17 dbfixtures.LoadFixtures("fixtures", "users")18 dbfixtures.LoadFixtures("fixtures", "posts")19 dbfixtures.LoadFixtures("fixtures", "comments")20}
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!!