Skip to content

Instantly share code, notes, and snippets.

@ncdc
Created December 15, 2017 22:19
Show Gist options
  • Save ncdc/dba2c2ea79c7dff4553b69a5e568434a to your computer and use it in GitHub Desktop.
Save ncdc/dba2c2ea79c7dff4553b69a5e568434a to your computer and use it in GitHub Desktop.
How would you unit test this?
func (c *backupController) run(backup *v1.Backup) error {
var errs []error
// shallow copy to backup so we can generate a patch
var original := backup
// deep copy so we don't mutate original
backup = backup.DeepCopy()
file, _ := ioutil.TempFile("", "")
defer file.Close()
// May mutate backup.Status.Phase, backup.Status.VolumeInfo, backup.Status.ValidationErrors, ...
// Current thinking is to use a mock for c.backupper in the unit tests. But for the mocking we're doing,
// we usually just control what the mocked method returns, which in this case is just an error. But
// this run() function depends on c.backupper.Backup() mutating the backup, to determine if we should
// proceed with the upload below. While you could argue (or not) that that's ok for the actual code,
// it seems a bit "wrong" since the mocking code only deals with the return value (an error) and not the mutations
// to the input objects. Does it make more sense have multiple return arguments, or is there some
// other better way to do this?
if err := c.backupper.Backup(backup, file); err != nil {
errs = append(errs, err)
}
if backup.Status.Phase == v1.BackupPhaseCompleted {
// Current thinking is to use a mock for c.uploader in the unit tests.
errs = append(errs, c.uploader.Upload(backup, file))
}
if err := patchBackup(original, backup); err != nil {
errs = append(errs, err)
}
return kubeerrors.NewAggregate(errs)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment