github.com/creativeprojects/go-selfupdate@v1.2.0/source_test.go (about)

     1  package selfupdate
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"io"
     7  )
     8  
     9  // MockSource is a Source in memory used for unit tests
    10  type MockSource struct {
    11  	releases  []SourceRelease
    12  	files     map[int64][]byte
    13  	readError bool
    14  }
    15  
    16  // NewMockSource instantiates a new MockSource
    17  func NewMockSource(releases []SourceRelease, files map[int64][]byte) *MockSource {
    18  	return &MockSource{
    19  		releases: releases,
    20  		files:    files,
    21  	}
    22  }
    23  
    24  // ListReleases returns a list of releases. repository parameter is not used.
    25  func (s *MockSource) ListReleases(ctx context.Context, repository Repository) ([]SourceRelease, error) {
    26  	if _, _, err := repository.GetSlug(); err != nil {
    27  		return nil, err
    28  	}
    29  	return s.releases, nil
    30  }
    31  
    32  // DownloadReleaseAsset returns a file from its ID. repository parameter is not used.
    33  func (s *MockSource) DownloadReleaseAsset(ctx context.Context, rel *Release, assetID int64) (io.ReadCloser, error) {
    34  	if rel == nil {
    35  		return nil, ErrInvalidRelease
    36  	}
    37  	if _, _, err := rel.repository.GetSlug(); err != nil {
    38  		return nil, err
    39  	}
    40  	content, ok := s.files[assetID]
    41  	if !ok {
    42  		return nil, ErrAssetNotFound
    43  	}
    44  	var buffer io.Reader = bytes.NewBuffer(content)
    45  	if s.readError {
    46  		// will return a read error after reading 4 characters
    47  		buffer = newErrorReader(buffer, 4)
    48  	}
    49  	return io.NopCloser(buffer), nil
    50  }
    51  
    52  // Verify interface
    53  var _ Source = &MockSource{}