I'm attempting to write a unit test, preferably in PEST PHP, to verify the following method:
Data is retrieved from the 'producers' table in the database and fed into the configuration. This configuration includes FTP server access details.
The file is then downloaded and saved locally.
How do you test something like this? Ideally, I would create a producer factory and then check if the file has been downloaded. However, I would like to avoid downloading real data if possible.
This is my simplified Class:
class FtpConnection extends Connection
{
/**
* @throws Exception
*/
public function download()
{
// get the content and make sure it's utf-8 encoded
$file = $this->encode(
$this->getFile()
);
// save content localy
return Storage::disk($this->disk)
->put($this->fileName(), $file);
}
/**
* @throws Exception
*/
protected function getFile()
{
$config = $this->config();
$storage = Storage::createFtpDriver($config);
throw_if(!$storage->exists($this->producer->path), new Exception('File not found at path: ' . $this->producer->path));
return $storage->get($this->producer->path);
}
protected function encode($file)
{
$currentEncoding = mb_detect_encoding($file, 'UTF-8, ISO-8859-1, GBK');
if($currentEncoding != 'UTF-8') {
return mb_convert_encoding($file, 'UTF-8', $currentEncoding);
} else {
return $file;
}
}
protected function config(): array
{
return [
'driver' => $this->producer->type,
'host' => $this->producer->host,
'port' => $this->producer->port,
'username' => $this->producer->username,
'password' => Crypt::decryptString($this->producer->password),
];
}
}
calling the class:
$ftpConnection = new FtpConnection(Producer::find(1))
$file = $ftpConnection->download();