github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/storage/version_test.go (about)

     1  // Copyright 2016 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package storage
    12  
    13  import (
    14  	"io/ioutil"
    15  	"os"
    16  	"testing"
    17  
    18  	"github.com/cockroachdb/cockroach/pkg/testutils"
    19  	"github.com/cockroachdb/cockroach/pkg/util/leaktest"
    20  )
    21  
    22  // TestVersions verifies that both getVersions() and writeVersionFile work
    23  // correctly.
    24  func TestVersions(t *testing.T) {
    25  	defer leaktest.AfterTest(t)()
    26  
    27  	dir, err := ioutil.TempDir("", "testing")
    28  	if err != nil {
    29  		t.Fatal(err)
    30  	}
    31  	defer func() {
    32  		if err := os.RemoveAll(dir); err != nil {
    33  			t.Fatal(err)
    34  		}
    35  	}()
    36  
    37  	// First test when no file exists yet.
    38  	ver, err := getVersion(dir)
    39  	if err != nil {
    40  		t.Fatal(err)
    41  	}
    42  	if ver != versionNoFile {
    43  		t.Errorf("no version file version should be %d, got %d", versionNoFile, ver)
    44  	}
    45  
    46  	// Write the current versions to the file.
    47  	if err := writeVersionFile(dir, versionCurrent); err != nil {
    48  		t.Fatal(err)
    49  	}
    50  	ver, err = getVersion(dir)
    51  	if err != nil {
    52  		t.Fatal(err)
    53  	}
    54  	if ver != versionCurrent {
    55  		t.Errorf("current versions do not match, expected %d got %d", versionCurrent, ver)
    56  	}
    57  
    58  	// Write gibberish to the file.
    59  	filename := getVersionFilename(dir)
    60  	if err := os.Remove(filename); err != nil {
    61  		t.Fatal(err)
    62  	}
    63  	if err := ioutil.WriteFile(filename, []byte("cause an error please"), 0644); err != nil {
    64  		t.Fatal(err)
    65  	}
    66  	if _, err := getVersion(dir); !testutils.IsError(err, "is not formatted correctly") {
    67  		t.Errorf("expected error contains '%s', got '%v'", "is not formatted correctly", err)
    68  	}
    69  }