github.com/andrewsun2898/u-root@v6.0.1-0.20200616011413-4b2895c1b815+incompatible/pkg/uroot/initramfs/test/ramfs.go (about)

     1  // Copyright 2018 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package test
     6  
     7  import (
     8  	"fmt"
     9  	"os"
    10  
    11  	"github.com/u-root/u-root/pkg/cpio"
    12  	"github.com/u-root/u-root/pkg/uio"
    13  )
    14  
    15  type ArchiveValidator interface {
    16  	Validate(a *cpio.Archive) error
    17  }
    18  
    19  type HasRecord struct {
    20  	R cpio.Record
    21  }
    22  
    23  func (hr HasRecord) Validate(a *cpio.Archive) error {
    24  	r, ok := a.Get(hr.R.Name)
    25  	if !ok {
    26  		return fmt.Errorf("archive does not contain %v", hr.R)
    27  	}
    28  	if !cpio.Equal(r, hr.R) {
    29  		return fmt.Errorf("archive does not contain %v; instead has %v", hr.R, r)
    30  	}
    31  	return nil
    32  }
    33  
    34  type HasFile struct {
    35  	Path string
    36  }
    37  
    38  func (hf HasFile) Validate(a *cpio.Archive) error {
    39  	if _, ok := a.Get(hf.Path); ok {
    40  		return nil
    41  	}
    42  	return fmt.Errorf("archive does not contain %s, but should", hf.Path)
    43  }
    44  
    45  type HasContent struct {
    46  	Path    string
    47  	Content string
    48  }
    49  
    50  func (hc HasContent) Validate(a *cpio.Archive) error {
    51  	r, ok := a.Get(hc.Path)
    52  	if !ok {
    53  		return fmt.Errorf("archive does not contain %s, but should", hc.Path)
    54  	}
    55  	if c, err := uio.ReadAll(r); err != nil {
    56  		return fmt.Errorf("reading record %s failed: %v", hc.Path, err)
    57  	} else if string(c) != hc.Content {
    58  		return fmt.Errorf("content of %s is %s, want %s", hc.Path, string(c), hc.Content)
    59  	}
    60  	return nil
    61  }
    62  
    63  type MissingFile struct {
    64  	Path string
    65  }
    66  
    67  func (mf MissingFile) Validate(a *cpio.Archive) error {
    68  	if _, ok := a.Get(mf.Path); ok {
    69  		return fmt.Errorf("archive contains %s, but shouldn't", mf.Path)
    70  	}
    71  	return nil
    72  }
    73  
    74  type IsEmpty struct{}
    75  
    76  func (IsEmpty) Validate(a *cpio.Archive) error {
    77  	if empty := a.Empty(); !empty {
    78  		return fmt.Errorf("expected archive to be empty")
    79  	}
    80  	return nil
    81  }
    82  
    83  func ReadArchive(path string) (*cpio.Archive, error) {
    84  	f, err := os.Open(path)
    85  	if err != nil {
    86  		return nil, err
    87  	}
    88  
    89  	return cpio.ArchiveFromReader(cpio.Newc.Reader(f))
    90  }