github.com/kubiko/snapd@v0.0.0-20201013125620-d4f3094d9ddf/cmd/snap/cmd_snapshot_test.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2019 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package main_test
    21  
    22  import (
    23  	"fmt"
    24  	"io/ioutil"
    25  	"net/http"
    26  	"path/filepath"
    27  	"strings"
    28  	"time"
    29  
    30  	. "gopkg.in/check.v1"
    31  
    32  	"github.com/snapcore/snapd/client"
    33  	main "github.com/snapcore/snapd/cmd/snap"
    34  	"github.com/snapcore/snapd/testutil"
    35  )
    36  
    37  var snapshotsTests = []getCmdArgs{{
    38  	args:  "restore x",
    39  	error: `invalid argument for snapshot set id: expected a non-negative integer argument \(see 'snap help saved'\)`,
    40  }, {
    41  	args:  "saved --id=x",
    42  	error: `invalid argument for snapshot set id: expected a non-negative integer argument \(see 'snap help saved'\)`,
    43  }, {
    44  	args:   "saved --id=3",
    45  	stdout: "Set  Snap  Age    Version  Rev   Size    Notes\n3    htop  .*  2        1168      1B  auto\n",
    46  }, {
    47  	args:   "saved",
    48  	stdout: "Set  Snap  Age    Version  Rev   Size    Notes\n1    htop  .*  2        1168      1B  -\n",
    49  }, {
    50  	args:  "forget x",
    51  	error: `invalid argument for snapshot set id: expected a non-negative integer argument \(see 'snap help saved'\)`,
    52  }, {
    53  	args:  "check-snapshot x",
    54  	error: `invalid argument for snapshot set id: expected a non-negative integer argument \(see 'snap help saved'\)`,
    55  }, {
    56  	args:   "restore 1",
    57  	stdout: "Restored snapshot #1.\n",
    58  }, {
    59  	args:   "forget 2",
    60  	stdout: "Snapshot #2 forgotten.\n",
    61  }, {
    62  	args:   "forget 2 snap1 snap2",
    63  	stdout: "Snapshot #2 of snaps \"snap1\", \"snap2\" forgotten.\n",
    64  }, {
    65  	args:   "check-snapshot 4",
    66  	stdout: "Snapshot #4 verified successfully.\n",
    67  }, {
    68  	args:   "check-snapshot 4 snap1 snap2",
    69  	stdout: "Snapshot #4 of snaps \"snap1\", \"snap2\" verified successfully.\n",
    70  }, {
    71  	args:  "export-snapshot x snapshot-export.snapshot",
    72  	error: `invalid argument for snapshot set id: expected a non-negative integer argument \(see 'snap help saved'\)`,
    73  }, {
    74  	args:  "export-snapshot 1",
    75  	error: "the required argument `<filename>` was not provided",
    76  }}
    77  
    78  func (s *SnapSuite) TestSnapSnaphotsTest(c *C) {
    79  	s.mockSnapshotsServer(c)
    80  
    81  	restore := main.MockIsStdinTTY(true)
    82  	defer restore()
    83  
    84  	for _, test := range snapshotsTests {
    85  		s.stdout.Truncate(0)
    86  		s.stderr.Truncate(0)
    87  
    88  		c.Logf("Test: %s", test.args)
    89  
    90  		_, err := main.Parser(main.Client()).ParseArgs(strings.Fields(test.args))
    91  		if test.error != "" {
    92  			c.Check(err, ErrorMatches, test.error)
    93  		} else {
    94  			c.Check(err, IsNil)
    95  			c.Check(s.Stderr(), testutil.EqualsWrapped, test.stderr)
    96  			c.Check(s.Stdout(), testutil.MatchesWrapped, test.stdout)
    97  		}
    98  		c.Check("snapshot-export.snapshot", testutil.FileAbsent)
    99  		c.Check("snapshot-export.snapshot.part", testutil.FileAbsent)
   100  	}
   101  }
   102  
   103  func (s *SnapSuite) TestSnapshotExportHappy(c *C) {
   104  	s.mockSnapshotsServer(c)
   105  
   106  	exportedSnapshotPath := filepath.Join(c.MkDir(), "export-snapshot.snapshot")
   107  	_, err := main.Parser(main.Client()).ParseArgs([]string{"export-snapshot", "1", exportedSnapshotPath})
   108  	c.Check(err, IsNil)
   109  	c.Check(s.Stderr(), testutil.EqualsWrapped, "")
   110  	c.Check(s.Stdout(), testutil.MatchesWrapped, `Exported snapshot #1 into ".*/export-snapshot.snapshot"`)
   111  	c.Check(exportedSnapshotPath, testutil.FileEquals, "Hello World!")
   112  	c.Check(exportedSnapshotPath+".part", testutil.FileAbsent)
   113  }
   114  
   115  func (s *SnapSuite) mockSnapshotsServer(c *C) {
   116  	s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) {
   117  		switch r.URL.Path {
   118  		case "/v2/snapshots":
   119  			if r.Method == "GET" {
   120  				// simulate a 1-month old snapshot
   121  				snapshotTime := time.Now().AddDate(0, -1, 0).Format(time.RFC3339)
   122  				if r.URL.Query().Get("set") == "3" {
   123  					fmt.Fprintf(w, `{"type":"sync","status-code":200,"status":"OK","result":[{"id":3,"snapshots":[{"set":3,"time":%q,"snap":"htop","revision":"1168","snap-id":"Z","auto":true,"epoch":{"read":[0],"write":[0]},"summary":"","version":"2","sha3-384":{"archive.tgz":""},"size":1}]}]}`, snapshotTime)
   124  					return
   125  				}
   126  				fmt.Fprintf(w, `{"type":"sync","status-code":200,"status":"OK","result":[{"id":1,"snapshots":[{"set":1,"time":%q,"snap":"htop","revision":"1168","snap-id":"Z","epoch":{"read":[0],"write":[0]},"summary":"","version":"2","sha3-384":{"archive.tgz":""},"size":1}]}]}`, snapshotTime)
   127  			}
   128  			if r.Method == "POST" {
   129  				if r.Header.Get("Content-Type") == client.SnapshotExportMediaType {
   130  					fmt.Fprintln(w, `{"type": "sync", "result": {"set-id": 42, "snaps": ["htop"]}}`)
   131  				} else {
   132  
   133  					w.WriteHeader(202)
   134  					fmt.Fprintln(w, `{"type":"async", "status-code": 202, "change": "9"}`)
   135  				}
   136  			}
   137  		case "/v2/changes/9":
   138  			fmt.Fprintln(w, `{"type": "sync", "result": {"ready": true, "status": "Done", "data": {}}}`)
   139  		case "/v2/snapshots/1/export":
   140  			w.Header().Set("Content-Type", client.SnapshotExportMediaType)
   141  			fmt.Fprint(w, "Hello World!")
   142  		default:
   143  			c.Errorf("unexpected path %q", r.URL.Path)
   144  		}
   145  	})
   146  }
   147  
   148  func (s *SnapSuite) TestSnapshotImportHappy(c *C) {
   149  	// mockSnapshotServer will return set-id 42 and three snaps for all
   150  	// import calls
   151  	s.mockSnapshotsServer(c)
   152  
   153  	exportedSnapshotPath := filepath.Join(c.MkDir(), "mocked-snapshot.snapshot")
   154  	ioutil.WriteFile(exportedSnapshotPath, []byte("this is really snapshot zip file data"), 0644)
   155  
   156  	_, err := main.Parser(main.Client()).ParseArgs([]string{"import-snapshot", exportedSnapshotPath})
   157  	c.Check(err, IsNil)
   158  	c.Check(s.Stderr(), testutil.EqualsWrapped, "")
   159  	c.Check(s.Stdout(), testutil.MatchesWrapped, `Imported snapshot as #42
   160  Set  Snap  Age    Version  Rev   Size    Notes
   161  1    htop  30d0h  2        1168      1B  -
   162  `)
   163  }