Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env perl
package main;
use strict;
use warnings;
use Test::mysqld::Persistent;
my $mysqld = Test::mysqld::Persistent->new;
my $purge = sub {
if (-e $mysqld->storage_file && -s _ > 0) {
unlink $mysqld->storage_file;
}
};
$SIG{INT} = $purge;
END { $purge->() }
sleep 3 while -e $mysqld->storage_file;
package Test::mysqld::Persistent;
use strict;
use warnings;
use Test::mysqld;
use JSON;
use File::Spec;
sub new {
my ($class, %args) = @_;
$args{storage_file} ||= $class->default_storage_file;
my $mysqld = $class->deserialize(%args);
my $self = bless +{ mysqld => $mysqld, storage_file => $args{storage_file} }, $class;
$self->serialize;
$self;
}
sub storage_file {
my $self = shift;
$self->{storage_file};
}
sub default_storage_file {
File::Spec->catfile(File::Spec->tmpdir, 'test_mysqld_persistent.json');
}
sub mysqld {
my $self = shift;
$self->{mysqld};
}
sub log_file {
my $self = shift;
File::Spec->catfile($self->mysqld->{base_dir}, 'tmp', 'mysqld.log');
}
sub socket {
my $self = shift;
$self->mysqld->{my_cnf}->{socket};
}
sub deserialize {
my ($class, %args) = @_;
my $mysqld;
my $file = delete $args{storage_file};
if (-e $file && -s _ > 0) {
open my $fh, '<', $file or die $!;
my $obj = decode_json(join '', <$fh>);
$mysqld = bless $obj, 'Test::mysqld';
}
else {
$mysqld = Test::mysqld->new(my_cnf => { 'skip-networking' => '', %args })
or die $Test::mysqld::errstr;
}
$mysqld;
}
sub serialize {
my $self = shift;
my $json = encode_json(+{ %{$self->mysqld} });
open my $fh, '>', $self->storage_file or die $!;
$fh->print($json);
$fh->close;
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment