fixed merge conflicts

This commit is contained in:
Wächtler, Yannick 2021-12-14 19:48:59 +01:00
commit 484b996879
77 changed files with 3564 additions and 4453 deletions

105
.env.dusk.local Normal file
View file

@ -0,0 +1,105 @@
# --------------------------------------------
# REQUIRED: BASIC APP SETTINGS
# --------------------------------------------
APP_ENV=local
APP_DEBUG=false
APP_KEY=base64:hTUIUh9CP6dQx+6EjSlfWTgbaMaaRvlpEwk45vp+xmk=
APP_URL=http://127.0.0.1:8000
APP_TIMEZONE='US/Eastern'
APP_LOCALE=en
APP_LOCKED=false
MAX_RESULTS=200
# --------------------------------------------
# REQUIRED: UPLOADED FILE STORAGE SETTINGS
# --------------------------------------------
PRIVATE_FILESYSTEM_DISK=local
PUBLIC_FILESYSTEM_DISK=local_public
# --------------------------------------------
# REQUIRED: DATABASE SETTINGS
# --------------------------------------------
DB_CONNECTION=mysql
DB_HOST=localhost
DB_DATABASE=snipeit-local
DB_USERNAME=snipeit-local
DB_PASSWORD=snipeit-local
DB_PREFIX=null
DB_DUMP_PATH='/Applications/MAMP/Library/bin'
# --------------------------------------------
# OPTIONAL: SSL DATABASE SETTINGS
# --------------------------------------------
DB_SSL=false
DB_SSL_KEY_PATH=null
DB_SSL_CERT_PATH=null
DB_SSL_CA_PATH=null
DB_SSL_CIPHER=null
# --------------------------------------------
# REQUIRED: OUTGOING MAIL SERVER SETTINGS
# --------------------------------------------
MAIL_DRIVER="log"
# --------------------------------------------
# REQUIRED: IMAGE LIBRARY
# This should be gd or imagick
# --------------------------------------------
IMAGE_LIB=gd
# --------------------------------------------
# OPTIONAL: SESSION SETTINGS
# --------------------------------------------
SESSION_LIFETIME=12000
EXPIRE_ON_CLOSE=false
ENCRYPT=true
COOKIE_NAME=snipeit_v5_local
SECURE_COOKIES=true
# --------------------------------------------
# OPTIONAL: SECURITY HEADER SETTINGS
# --------------------------------------------
REFERRER_POLICY=same-origin
ENABLE_CSP=true
CORS_ALLOWED_ORIGINS="*"
# --------------------------------------------
# OPTIONAL: CACHE SETTINGS
# --------------------------------------------
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
# --------------------------------------------
# OPTIONAL: LOGIN THROTTLING
# --------------------------------------------
LOGIN_MAX_ATTEMPTS=50000
LOGIN_LOCKOUT_DURATION=1000
RESET_PASSWORD_LINK_EXPIRES=15
# --------------------------------------------
# OPTIONAL: API
# --------------------------------------------
API_MAX_REQUESTS_PER_HOUR=200
# --------------------------------------------
# OPTIONAL: SAML SETTINGS
# --------------------------------------------
DISABLE_NOSAML_LOCAL_LOGIN=true
# --------------------------------------------
# OPTIONAL: MISC
# --------------------------------------------
APP_LOG=single
LOG_LEVEL=debug
LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=null
APP_TRUSTED_PROXIES=192.168.1.1,10.0.0.1
ALLOW_IFRAMING=true
ENABLE_HSTS=false
WARN_DEBUG=false
APP_CIPHER=AES-256-CBC

View file

@ -1,10 +1,10 @@
# --------------------------------------------
# REQUIRED: BASIC APP SETTINGS
# --------------------------------------------
APP_ENV=testing-ci
APP_ENV='testing-ci'
APP_DEBUG=false
APP_KEY=ChangeMe
APP_URL=http://localhost:8000
APP_KEY='base64:glJpcM7BYwWiBggp3SQ/+NlRkqsBQMaGEOjemXqJzOU='
APP_URL='http://localhost:8000'
APP_TIMEZONE='US/Pacific'
APP_LOCALE=en
FILESYSTEM_DISK=local
@ -12,9 +12,9 @@ FILESYSTEM_DISK=local
# --------------------------------------------
# REQUIRED: DATABASE SETTINGS
# --------------------------------------------
DB_CONNECTION=mysql
DB_CONNECTION=sqlite
DB_HOST=localhost
DB_DATABASE=snipeit_unit
DB_DATABASE='sqlite_testing'
DB_USERNAME=root
DB_PASSWORD=null
@ -22,13 +22,7 @@ DB_PASSWORD=null
# REQUIRED: OUTGOING MAIL SERVER SETTINGS
# --------------------------------------------
MAIL_DRIVER=log
MAIL_HOST=email-smtp.us-west-2.amazonaws.com
MAIL_PORT=587
MAIL_USERNAME=YOURUSERNAME
MAIL_PASSWORD=YOURPASSWORD
MAIL_ENCRYPTION=null
MAIL_FROM_ADDR=you@example.com
MAIL_FROM_NAME=Snipe-IT
# --------------------------------------------
# REQUIRED: IMAGE LIBRARY
@ -37,37 +31,7 @@ MAIL_FROM_NAME=Snipe-IT
IMAGE_LIB=gd
# --------------------------------------------
# OPTIONAL: AWS S3 SETTINGS
# --------------------------------------------
AWS_SECRET_ACCESS_KEY=null
AWS_ACCESS_KEY_ID=null
AWS_DEFAULT_REGION=null
AWS_BUCKET=null
AWS_BUCKET_ROOT=null
AWS_URL=null
# --------------------------------------------
# OPTIONAL: CACHE SETTINGS
# --------------------------------------------
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
# --------------------------------------------
# OPTIONAL: SESSION SETTINGS
# --------------------------------------------
SESSION_LIFETIME=12000
EXPIRE_ON_CLOSE=false
ENCRYPT=false
COOKIE_NAME=snipeittest_session
COOKIE_DOMAIN=null
SECURE_COOKIES=false
# --------------------------------------------
# OPTIONAL: APP LOG FORMAT
# --------------------------------------------
APP_LOG=single
APP_LOG=single

View file

@ -114,8 +114,8 @@ class AssetsController extends Controller
}
$assets = Company::scopeCompanyables(Asset::select('assets.*'), 'company_id', 'assets')
->with('location', 'assetstatus', 'assetlog', 'company', 'defaultLoc','assignedTo',
'model.category', 'model.manufacturer', 'model.fieldset', 'supplier');
->with('location', 'assetstatus', 'company', 'defaultLoc','assignedTo',
'model.category', 'model.manufacturer', 'model.fieldset', 'supplier'); //it's tempting to add assetlogs here, but don't - it blows up update-heavy installations
// These are used by the API to query against specific ID numbers.
// They are also used by the individual searches on detail pages like

View file

@ -162,27 +162,34 @@ class SettingsController extends Controller
public function slacktest(Request $request)
{
$slack = new Client([
'base_url' => e($request->input('slack_endpoint')),
'defaults' => [
'exceptions' => false,
],
]);
$payload = json_encode(
[
'channel' => e($request->input('slack_channel')),
'text' => trans('general.slack_test_msg'),
'username' => e($request->input('slack_botname')),
'icon_emoji' => ':heart:',
// Only attempt the slack request if the validation passes
if ($request->validate([
'slack_endpoint' => 'url|required_with:slack_channel|starts_with:https://hooks.slack.com|nullable',
'slack_channel' => 'required_with:slack_endpoint|starts_with:#|nullable',
])) {
$slack = new Client([
'base_url' => e($request->input('slack_endpoint')),
'defaults' => [
'exceptions' => false,
],
]);
try {
$slack->post($request->input('slack_endpoint'), ['body' => $payload]);
$payload = json_encode(
[
'channel' => e($request->input('slack_channel')),
'text' => trans('general.slack_test_msg'),
'username' => e($request->input('slack_botname')),
'icon_emoji' => ':heart:',
]);
return response()->json(['message' => 'Success'], 200);
} catch (\Exception $e) {
return response()->json(['message' => 'Oops! Please check the channel name and webhook endpoint URL. Slack responded with: '.$e->getMessage()], 400);
try {
$slack->post($request->input('slack_endpoint'), ['body' => $payload]);
return response()->json(['message' => 'Success'], 200);
} catch (\Exception $e) {
return response()->json(['message' => 'Oops! Please check the channel name and webhook endpoint URL. Slack responded with: '.$e->getMessage()], 400);
}
}
return response()->json(['message' => 'Something went wrong :( '], 400);

View file

@ -513,6 +513,10 @@ class ReportsController extends Controller
$header[] = trans('general.department');
}
if ($request->filled('title')) {
$header[] = trans('admin/users/table.title');
}
if ($request->filled('status')) {
$header[] = trans('general.status');
}
@ -756,6 +760,14 @@ class ReportsController extends Controller
}
}
if ($request->filled('title')) {
if ($asset->checkedOutToUser()) {
$row[] = ($asset->assignedto) ? $asset->assignedto->jobtitle : '';
} else {
$row[] = ''; // Empty string if unassigned
}
}
if ($request->filled('status')) {
$row[] = ($asset->assetstatus) ? $asset->assetstatus->name.' ('.$asset->present()->statusMeta.')' : '';
}

View file

@ -665,16 +665,6 @@ class SettingsController extends Controller
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$validatedData = $request->validate([
'slack_channel' => 'regex:/(?<!\w)#\w+/|required_with:slack_endpoint|nullable',
]);
if ($validatedData) {
$setting->slack_endpoint = $request->input('slack_endpoint');
$setting->slack_channel = $request->input('slack_channel');
$setting->slack_botname = $request->input('slack_botname');
}
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));

View file

@ -135,7 +135,7 @@ class CheckoutableListener
/**
* Notify Admin users if the settings is activated
*/
if (Setting::getSettings()->admin_cc_email != '') {
if ((Setting::getSettings()) && (Setting::getSettings()->admin_cc_email != '')) {
$notifiables->push(new AdminRecipient());
}

View file

@ -114,6 +114,7 @@ class Asset extends Depreciable
'purchase_cost' => 'numeric|nullable',
'next_audit_date' => 'date|nullable',
'last_audit_date' => 'date|nullable',
'supplier_id' => 'exists:suppliers,id|nullable',
];
/**

View file

@ -30,7 +30,7 @@ class AssetModel extends SnipeModel
'name' => 'required|min:1|max:255',
'model_number' => 'max:255|nullable',
'category_id' => 'required|integer|exists:categories,id',
'manufacturer_id' => 'required|integer|exists:manufacturers,id',
'manufacturer_id' => 'integer|exists:manufacturers,id|nullable',
'eol' => 'integer:min:0|max:240|nullable',
];

View file

@ -54,9 +54,9 @@ class Setting extends Model
'admin_cc_email' => 'email|nullable',
'default_currency' => 'required',
'locale' => 'required',
'slack_endpoint' => 'url|required_with:slack_channel|nullable',
'slack_endpoint' => 'url|required_with:slack_channel|nullable|starts_with:https://hooks.slack.com',
'labels_per_page' => 'numeric',
'slack_channel' => 'regex:/^[\#\@]?\w+/|required_with:slack_endpoint|nullable',
'slack_channel' => 'required_with:slack_endpoint|starts_with:#|nullable',
'slack_botname' => 'string|nullable',
'labels_width' => 'numeric',
'labels_height' => 'numeric',

View file

@ -53,7 +53,7 @@ class CheckoutAssetNotification extends Notification
{
$notifyBy = [];
if (Setting::getSettings()->slack_endpoint != '') {
if ((Setting::getSettings()) && (Setting::getSettings()->slack_endpoint != '')) {
\Log::debug('use slack');
$notifyBy[] = 'slack';
}

View file

@ -102,7 +102,7 @@ class AccessoryPresenter extends Presenter
'searchable' => true,
'sortable' => true,
'title' => trans('general.purchase_cost'),
'footerFormatter' => 'sumFormatter',
'footerFormatter' => 'sumFormatterQuantity',
'class' => 'text-right',
], [
'field' => 'order_number',

View file

@ -101,7 +101,7 @@ class ComponentPresenter extends Presenter
'sortable' => true,
'title' => trans('general.purchase_cost'),
'visible' => true,
'footerFormatter' => 'sumFormatter',
'footerFormatter' => 'sumFormatterQuantity',
'class' => 'text-right',
],
];

View file

@ -113,7 +113,7 @@ class ConsumablePresenter extends Presenter
'sortable' => true,
'title' => trans('general.purchase_cost'),
'visible' => true,
'footerFormatter' => 'sumFormatter',
'footerFormatter' => 'sumFormatterQuantity',
'class' => 'text-right',
], [
'field' => 'change',

View file

@ -136,7 +136,7 @@ class LicensePresenter extends Presenter
'sortable' => true,
'visible' => false,
'title' => trans('general.purchase_cost'),
'footerFormatter' => 'sumFormatter',
'footerFormatter' => 'sumFormatterQuantity',
'class' => 'text-right',
], [
'field' => 'purchase_order',

View file

@ -61,8 +61,15 @@ class AppServiceProvider extends ServiceProvider
*/
public function register()
{
// Only load rollbar if there is a rollbar key and the app is in production
if (($this->app->environment('production')) && (config('logging.channels.rollbar.access_token'))) {
$this->app->register(\Rollbar\Laravel\RollbarServiceProvider::class);
}
}
// Only load dusk's service provider if the app is in local or develop mode
if ($this->app->environment(['local', 'develop'])) {
$this->app->register(\Laravel\Dusk\DuskServiceProvider::class);
}
}
}

275
c3.php
View file

@ -1,275 +0,0 @@
<?php
// @codingStandardsIgnoreFile
// @codeCoverageIgnoreStart
/**
* C3 - Codeception Code Coverage
*
* @author tiger
*/
// $_SERVER['HTTP_X_CODECEPTION_CODECOVERAGE_DEBUG'] = 1;
if (isset($_COOKIE['CODECEPTION_CODECOVERAGE'])) {
$cookie = json_decode($_COOKIE['CODECEPTION_CODECOVERAGE'], true);
// fix for improperly encoded JSON in Code Coverage cookie with WebDriver.
// @see https://github.com/Codeception/Codeception/issues/874
if (!is_array($cookie)) {
$cookie = json_decode($cookie, true);
}
if ($cookie) {
foreach ($cookie as $key => $value) {
$_SERVER["HTTP_X_CODECEPTION_".strtoupper($key)] = $value;
}
}
}
if (!array_key_exists('HTTP_X_CODECEPTION_CODECOVERAGE', $_SERVER)) {
return;
}
if (!function_exists('__c3_error')) {
function __c3_error($message)
{
$errorLogFile = defined('C3_CODECOVERAGE_ERROR_LOG_FILE') ?
C3_CODECOVERAGE_ERROR_LOG_FILE :
C3_CODECOVERAGE_MEDIATE_STORAGE . DIRECTORY_SEPARATOR . 'error.txt';
if (is_writable($errorLogFile)) {
file_put_contents($errorLogFile, $message);
}else{
$message = "Could not write error to log file ($errorLogFile), original message: $message";
}
if (!headers_sent()) {
header('X-Codeception-CodeCoverage-Error: ' . str_replace("\n", ' ', $message), true, 500);
}
setcookie('CODECEPTION_CODECOVERAGE_ERROR', $message);
}
}
// phpunit codecoverage shimming
if (class_exists('SebastianBergmann\CodeCoverage\CodeCoverage')) {
class_alias('SebastianBergmann\CodeCoverage\CodeCoverage', 'PHP_CodeCoverage');
class_alias('SebastianBergmann\CodeCoverage\Report\Text', 'PHP_CodeCoverage_Report_Text');
class_alias('SebastianBergmann\CodeCoverage\Report\PHP', 'PHP_CodeCoverage_Report_PHP');
class_alias('SebastianBergmann\CodeCoverage\Report\Clover', 'PHP_CodeCoverage_Report_Clover');
class_alias('SebastianBergmann\CodeCoverage\Report\Html\Facade', 'PHP_CodeCoverage_Report_HTML');
class_alias('SebastianBergmann\CodeCoverage\Exception', 'PHP_CodeCoverage_Exception');
}
// Autoload Codeception classes
if (!class_exists('\\Codeception\\Codecept')) {
if (file_exists(__DIR__ . '/codecept.phar')) {
require_once 'phar://'.__DIR__ . '/codecept.phar/autoload.php';
} elseif (stream_resolve_include_path(__DIR__ . '/vendor/autoload.php')) {
require_once __DIR__ . '/vendor/autoload.php';
// Required to load some methods only available at codeception/autoload.php
if (stream_resolve_include_path(__DIR__ . '/vendor/codeception/codeception/autoload.php')) {
require_once __DIR__ . '/vendor/codeception/codeception/autoload.php';
}
} elseif (stream_resolve_include_path('Codeception/autoload.php')) {
require_once 'Codeception/autoload.php';
} else {
__c3_error('Codeception is not loaded. Please check that either PHAR or Composer or PEAR package can be used');
}
}
// Load Codeception Config
$config_dist_file = realpath(__DIR__) . DIRECTORY_SEPARATOR . 'codeception.dist.yml';
$config_file = realpath(__DIR__) . DIRECTORY_SEPARATOR . 'codeception.yml';
if (isset($_SERVER['HTTP_X_CODECEPTION_CODECOVERAGE_CONFIG'])) {
$config_file = realpath(__DIR__) . DIRECTORY_SEPARATOR . $_SERVER['HTTP_X_CODECEPTION_CODECOVERAGE_CONFIG'];
}
if (file_exists($config_file)) {
// Use codeception.yml for configuration.
} elseif (file_exists($config_dist_file)) {
// Use codeception.dist.yml for configuration.
$config_file = $config_dist_file;
} else {
__c3_error(sprintf("Codeception config file '%s' not found", $config_file));
}
try {
\Codeception\Configuration::config($config_file);
} catch (\Exception $e) {
__c3_error($e->getMessage());
}
if (!defined('C3_CODECOVERAGE_MEDIATE_STORAGE')) {
// workaround for 'zend_mm_heap corrupted' problem
gc_disable();
if ((integer)ini_get('memory_limit') < 384) {
ini_set('memory_limit', '384M');
}
define('C3_CODECOVERAGE_MEDIATE_STORAGE', Codeception\Configuration::logDir() . 'c3tmp');
define('C3_CODECOVERAGE_PROJECT_ROOT', Codeception\Configuration::projectDir());
define('C3_CODECOVERAGE_TESTNAME', $_SERVER['HTTP_X_CODECEPTION_CODECOVERAGE']);
function __c3_build_html_report(PHP_CodeCoverage $codeCoverage, $path)
{
$writer = new PHP_CodeCoverage_Report_HTML();
$writer->process($codeCoverage, $path . 'html');
if (file_exists($path . '.tar')) {
unlink($path . '.tar');
}
$phar = new PharData($path . '.tar');
$phar->setSignatureAlgorithm(Phar::SHA1);
$files = $phar->buildFromDirectory($path . 'html');
array_map('unlink', $files);
if (in_array('GZ', Phar::getSupportedCompression())) {
if (file_exists($path . '.tar.gz')) {
unlink($path . '.tar.gz');
}
$phar->compress(\Phar::GZ);
// close the file so that we can rename it
unset($phar);
unlink($path . '.tar');
rename($path . '.tar.gz', $path . '.tar');
}
return $path . '.tar';
}
function __c3_build_clover_report(PHP_CodeCoverage $codeCoverage, $path)
{
$writer = new PHP_CodeCoverage_Report_Clover();
$writer->process($codeCoverage, $path . '.clover.xml');
return $path . '.clover.xml';
}
function __c3_send_file($filename)
{
if (!headers_sent()) {
readfile($filename);
}
return __c3_exit();
}
/**
* @param $filename
* @return null|PHP_CodeCoverage
*/
function __c3_factory($filename)
{
$phpCoverage = is_readable($filename)
? unserialize(file_get_contents($filename))
: new PHP_CodeCoverage();
if (isset($_SERVER['HTTP_X_CODECEPTION_CODECOVERAGE_SUITE'])) {
$suite = $_SERVER['HTTP_X_CODECEPTION_CODECOVERAGE_SUITE'];
try {
$settings = \Codeception\Configuration::suiteSettings($suite, \Codeception\Configuration::config());
} catch (Exception $e) {
__c3_error($e->getMessage());
}
} else {
$settings = \Codeception\Configuration::config();
}
try {
\Codeception\Coverage\Filter::setup($phpCoverage)
->whiteList($settings)
->blackList($settings);
} catch (Exception $e) {
__c3_error($e->getMessage());
}
return $phpCoverage;
}
function __c3_exit()
{
if (!isset($_SERVER['HTTP_X_CODECEPTION_CODECOVERAGE_DEBUG'])) {
exit;
}
return null;
}
function __c3_clear()
{
\Codeception\Util\FileSystem::doEmptyDir(C3_CODECOVERAGE_MEDIATE_STORAGE);
}
}
if (!is_dir(C3_CODECOVERAGE_MEDIATE_STORAGE)) {
if (mkdir(C3_CODECOVERAGE_MEDIATE_STORAGE, 0777, true) === false) {
__c3_error('Failed to create directory "' . C3_CODECOVERAGE_MEDIATE_STORAGE . '"');
}
}
// evaluate base path for c3-related files
$path = realpath(C3_CODECOVERAGE_MEDIATE_STORAGE) . DIRECTORY_SEPARATOR . 'codecoverage';
$requested_c3_report = (strpos($_SERVER['REQUEST_URI'], 'c3/report') !== false);
$complete_report = $current_report = $path . '.serialized';
if ($requested_c3_report) {
set_time_limit(0);
$route = ltrim(strrchr($_SERVER['REQUEST_URI'], '/'), '/');
if ($route == 'clear') {
__c3_clear();
return __c3_exit();
}
$codeCoverage = __c3_factory($complete_report);
switch ($route) {
case 'html':
try {
__c3_send_file(__c3_build_html_report($codeCoverage, $path));
} catch (Exception $e) {
__c3_error($e->getMessage());
}
return __c3_exit();
case 'clover':
try {
__c3_send_file(__c3_build_clover_report($codeCoverage, $path));
} catch (Exception $e) {
__c3_error($e->getMessage());
}
return __c3_exit();
case 'serialized':
try {
__c3_send_file($complete_report);
} catch (Exception $e) {
__c3_error($e->getMessage());
}
return __c3_exit();
}
} else {
$codeCoverage = __c3_factory($current_report);
$codeCoverage->start(C3_CODECOVERAGE_TESTNAME);
if (!array_key_exists('HTTP_X_CODECEPTION_CODECOVERAGE_DEBUG', $_SERVER)) {
register_shutdown_function(
function () use ($codeCoverage, $current_report) {
$codeCoverage->stop();
if (!file_exists(dirname($current_report))) { // verify directory exists
if(!mkdir(dirname($current_report), 0777, true)){
__c3_error("Can't write CodeCoverage report into $current_report");
}
}
file_put_contents($current_report, serialize($codeCoverage));
}
);
}
}
// @codeCoverageIgnoreEnd

View file

@ -1,20 +0,0 @@
actor: Tester
paths:
tests: tests
log: tests/_output
data: tests/_data
support: tests/_support
envs: tests/_envs
bootstrap: _bootstrap.php
settings:
colors: true
memory_limit: 1024M
extensions:
enabled:
- Codeception\Extension\RunFailed
coverage:
enabled: true
include:
- app/*
exclude:
- app/cache/*

View file

@ -66,22 +66,16 @@
"watson/validating": "^6.1"
},
"require-dev": {
"codeception/codeception": "^4.1",
"codeception/module-asserts": "^1.2",
"codeception/module-laravel5": "^1.1",
"codeception/module-rest": "^1.2",
"codeception/module-webdriver": "^1.0",
"fzaninotto/faker": "master@dev",
"fakerphp/faker": "^1.16",
"laravel/dusk": "^6.19",
"mockery/mockery": "^1.4",
"overtrue/phplint": "^3.0",
"phpunit/php-token-stream": "^3.1",
"phpunit/phpunit": "^8.5",
"phpunit/phpunit": "^9.0",
"squizlabs/php_codesniffer": "^3.5",
"symfony/css-selector": "^4.4",
"symfony/dom-crawler": "^4.4"
},
"suggest": {
"ext-mcrypt": "For upgrading from before v5.1 this is used to re-encrypt data"
},
"extra": {
"laravel": {
"dont-discover": [
@ -101,9 +95,13 @@
},
"autoload-dev": {
"classmap": [
"tests/TestCase.php",
"tests/unit/BaseTest.php"
]
"tests/DuskTestCase.php",
"tests/TestCase.php"
],
"psr-4": {
"App\\": "app/",
"Tests\\": "tests/"
}
},
"scripts": {
"post-autoload-dump": [
@ -120,4 +118,4 @@
"discard-changes": true,
"process-timeout": 3000
}
}
}

2542
composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -5,7 +5,10 @@ namespace Database\Factories;
use App\Models\Asset;
use App\Models\AssetModel;
use App\Models\Category;
use App\Models\Location;
use App\Models\Supplier;
use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\StatusLabel;
/*
|--------------------------------------------------------------------------
@ -36,16 +39,16 @@ class AssetFactory extends Factory
{
return [
'name' => null,
'rtd_location_id' => rand(1, 10),
'rtd_location_id' => Location::factory()->create(),
'serial' => $this->faker->uuid,
'status_id' => 1,
'status_id' => StatusLabel::factory()->create()->id,
'user_id' => 1,
'asset_tag' => $this->faker->unixTime('now'),
'notes' => 'Created by DB seeder',
'purchase_date' => $this->faker->dateTimeBetween('-1 years', 'now', date_default_timezone_get()),
'purchase_cost' => $this->faker->randomFloat(2, '299.99', '2999.99'),
'order_number' => $this->faker->numberBetween(1000000, 50000000),
'supplier_id' => 1,
'supplier_id' => Supplier::factory()->create(),
'requestable' => $this->faker->boolean(),
'assigned_to' => null,
'assigned_type' => null,

View file

@ -3,6 +3,7 @@
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Category;
/*
|--------------------------------------------------------------------------
@ -81,6 +82,7 @@ class AssetModelFactory extends Factory
{
return [
'user_id' => 1,
'name' => $this->faker->catchPhrase(),
'model_number' => $this->faker->creditCardNumber(),
'notes' => 'Created by demo seeder',
@ -93,7 +95,6 @@ class AssetModelFactory extends Factory
return [
'name' => 'Macbook Pro 13"',
'category_id' => 1,
'manufacturer_id' => 1,
'eol' => '36',
'depreciation_id' => 1,
'image' => 'mbp.jpg',

View file

@ -3,6 +3,7 @@
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Category;
/*
|--------------------------------------------------------------------------
@ -30,6 +31,7 @@ class CategoryFactory extends Factory
public function definition()
{
return [
'name' => $this->faker->catchPhrase(),
'checkin_email' => $this->faker->boolean(),
'eula_text' => $this->faker->paragraph(),
'require_acceptance' => false,
@ -38,154 +40,143 @@ class CategoryFactory extends Factory
];
}
// usage: Category::factory()->assetLaptopCategory();
public function assetLaptopCategory()
{
return $this->state(function () {
return [
'name' => 'Laptops',
'category_type' => 'asset',
'require_acceptance' => true,
];
});
return Category::factory()->create([
'name' => 'Laptops',
'category_type' => 'asset',
'require_acceptance' => true,
]);
}
// usage: Category::factory()->assetDesktopCategory();
public function assetDesktopCategory()
{
return $this->state(function () {
return [
'name' => 'Desktops',
'category_type' => 'asset',
];
});
return Category::factory()->create([
'name' => 'Desktops',
'category_type' => 'asset',
'require_acceptance' => true,
]);
}
// usage: Category::factory()->assetDisplayCategory();
public function assetDisplayCategory()
{
return $this->state(function () {
return [
'name' => 'Displays',
'category_type' => 'asset',
];
});
return Category::factory()->create([
'name' => 'Displays',
'category_type' => 'asset',
]);
}
public function assetTabletCategory()
{
return $this->state(function () {
return [
'name' => 'Tablets',
'category_type' => 'asset',
];
});
}
// usage: Category::factory()->assetTabletCategory();
public function assetTabletCategory()
{
return Category::factory()->create([
'name' => 'Tablets',
'category_type' => 'asset',
]);
}
public function assetMobileCategory()
{
return $this->state(function () {
return [
'name' => 'Mobile Phones',
'category_type' => 'asset',
];
});
}
// usage: Category::factory()->assetMobileCategory();
public function assetMobileCategory()
{
return Category::factory()->create([
'name' => 'Mobile Phones',
'category_type' => 'asset',
]);
}
public function assetConferenceCategory()
{
return $this->state(function () {
return [
'name' => 'Conference Phones',
'category_type' => 'asset',
];
});
}
// usage: Category::factory()->assetConferenceCategory();
public function assetConferenceCategory()
{
return Category::factory()->create([
'name' => 'Conference Phones',
'category_type' => 'asset',
]);
}
public function assetVoipCategory()
{
return $this->state(function () {
return [
'name' => 'VOIP Phones',
'category_type' => 'asset',
];
});
}
public function accessoryKeyboardCategory()
{
return $this->state(function () {
return [
'name' => 'Keyboards',
'category_type' => 'accessory',
];
});
}
// usage: Category::factory()->assetVoipCategory();
public function assetVoipCategory()
{
return Category::factory()->create([
'name' => 'VOIP Phones',
'category_type' => 'asset',
]);
}
public function accessoryMouseCategory()
{
return $this->state(function () {
return [
'name' => 'Mouse',
'category_type' => 'accessory',
];
});
}
// usage: Category::factory()->accessoryKeyboardCategory();
public function accessoryKeyboardCategory()
{
return Category::factory()->create([
'name' => 'Keyboardss',
'category_type' => 'accessory',
]);
}
public function componentHddCategory()
{
return $this->state(function () {
return [
'name' => 'HDD/SSD',
'category_type' => 'component',
];
});
}
public function componentRamCategory()
{
return $this->state(function () {
return [
'name' => 'RAM',
'category_type' => 'component',
];
});
}
// usage: Category::factory()->accessoryMouseCategory();
public function accessoryMouseCategory()
{
return Category::factory()->create([
'name' => 'Mouse',
'category_type' => 'accessory',
]);
}
public function consumablePaperCategory()
{
return $this->state(function () {
return [
'name' => 'Printer Paper',
'category_type' => 'consumable',
];
});
}
// usage: Category::factory()->componentHddCategory();
public function componentHddCategory()
{
return Category::factory()->create([
'name' => 'HDD/SSD',
'category_type' => 'component',
]);
}
public function consumableInkCategory()
{
return $this->state(function () {
return [
'name' => 'Printer Ink',
'category_type' => 'consumable',
];
});
}
// usage: Category::factory()->componentRamCategory();
public function componentRamCategory()
{
return Category::factory()->create([
'name' => 'RAM',
'category_type' => 'component',
]);
}
public function licenseGraphicsCategory()
{
return $this->state(function () {
return [
'name' => 'Graphics Software',
'category_type' => 'license',
];
});
}
// usage: Category::factory()->consumablePaperCategory();
public function consumablePaperCategory()
{
return Category::factory()->create([
'name' => 'Printer Paper',
'category_type' => 'consumable',
]);
}
// usage: Category::factory()->consumableInkCategory();
public function consumableInkCategory()
{
return Category::factory()->create([
'name' => 'Printer Ink',
'category_type' => 'consumable',
]);
}
// usage: Category::factory()->licenseGraphicsCategory();
public function licenseGraphicsCategory()
{
return Category::factory()->create([
'name' => 'Graphics Software',
'category_type' => 'license',
]);
}
// usage: Category::factory()->licenseGraphicsCategory();
public function licenseOfficeCategory()
{
return Category::factory()->create([
'name' => 'Office Software',
'category_type' => 'license',
]);
}
public function licenseOfficeCategory()
{
return $this->state(function () {
return [
'name' => 'Office Software',
'category_type' => 'license',
];
});
}
}

View file

@ -30,7 +30,9 @@ class DepreciationFactory extends Factory
public function definition()
{
return [
'name' => $this->faker->catchPhrase(),
'user_id' => 1,
'months' => 36,
];
}

View file

@ -1,36 +1,11 @@
<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
namespace Database\Factories;
use App\Models\AssetModel;
use App\Models\Category;
use App\Models\Company;
use App\Models\Location;
use App\Models\Manufacturer;
use App\Models\Statuslabel;
use App\Models\Supplier;
use Illuminate\Database\Eloquent\Factories\Factory;
class LocationFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = \App\Models\Location::class;
/**
* Define the model's default state.
*
@ -39,15 +14,17 @@ class LocationFactory extends Factory
public function definition()
{
return [
'name' => $this->faker->city,
'address' => $this->faker->streetAddress,
'address2' => $this->faker->secondaryAddress,
'city' => $this->faker->city,
'state' => $this->faker->stateAbbr,
'country' => $this->faker->countryCode,
'currency' => $this->faker->currencyCode,
'zip' => $this->faker->postcode,
'name' => $this->faker->city(),
'address' => $this->faker->streetAddress(),
'address2' => $this->faker->secondaryAddress(),
'city' => $this->faker->city(),
'state' => $this->faker->stateAbbr(),
'country' => $this->faker->countryCode(),
'currency' => $this->faker->currencyCode(),
'zip' => $this->faker->postcode(),
'image' => rand(1, 9).'.jpg',
];
}
}

View file

@ -2,19 +2,11 @@
namespace Database\Factories;
use App\Models\Company;
use Illuminate\Database\Eloquent\Factories\Factory;
use \Auth;
class UserFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = \App\Models\User::class;
/**
* Define the model's default state.
*
@ -22,23 +14,21 @@ class UserFactory extends Factory
*/
public function definition()
{
$password = bcrypt('password');
return [
'activated' => 1,
'address' => $this->faker->address,
'city' => $this->faker->city,
'address' => $this->faker->address(),
'city' => $this->faker->city(),
'company_id' => rand(1, 4),
'country' => $this->faker->country,
'country' => $this->faker->country(),
'department_id' => rand(1, 6),
'email' => $this->faker->safeEmail,
'employee_num' => $this->faker->numberBetween(3500, 35050),
'first_name' => $this->faker->firstName,
'jobtitle' => $this->faker->jobTitle,
'last_name' => $this->faker->lastName,
'locale' => $this->faker->locale,
'location_id' => rand(1, 5),
'first_name' => $this->faker->firstName(),
'jobtitle' => $this->faker->jobTitle(),
'last_name' => $this->faker->lastName(),
'locale' => $this->faker->locale(),
'notes' => 'Created by DB seeder',
'password' => $password,
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'permissions' => '{"user":"0"}',
'phone' => $this->faker->phoneNumber,
'state' => $this->faker->stateAbbr,
@ -46,7 +36,7 @@ class UserFactory extends Factory
'zip' => $this->faker->postcode,
];
}
public function firstAdmin()
{
return $this->state(function () {
@ -407,4 +397,5 @@ class UserFactory extends Factory
];
});
}
}

View file

@ -1,34 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="bootstrap/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Application Test Suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">app/</directory>
</whitelist>
</filter>
<php>
<env name="APP_ENV" value="testing-ci"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
<env name="DB_CONNECTION" value="sqlite_testing" />
<server name="SERVER_NAME" value="http://testing.dev"/>
</php>
<logging>
<log type="coverage-clover" target="build/logs/clover.xml"/>
</logging>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" backupGlobals="false" backupStaticAttributes="false" bootstrap="bootstrap/autoload.php" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
<coverage>
<include>
<directory suffix=".php">app/</directory>
</include>
</coverage>
<testsuites>
<testsuite name="Application Test Suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>
<php>
<env name="APP_ENV" value="testing-ci"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
<env name="DB_CONNECTION" value="sqlite"/>
<server name="SERVER_NAME" value="http://127.0.0.1:8000"/>
<ini name="display_errors" value="true"/>
</php>
</phpunit>

View file

@ -149,8 +149,7 @@
'licenses_available' => 'licenses available',
'licenses' => 'Licenses',
'list_all' => 'List All',
'loading' => 'Loading',
'loading_wait' => 'Loading... please wait....',
'loading' => 'Loading... please wait....',
'lock_passwords' => 'This field value will not be saved in a demo installation.',
'feature_disabled' => 'This feature has been disabled for the demo installation.',
'location' => 'Location',
@ -164,7 +163,7 @@
'manufacturers' => 'Manufacturers',
'markdown' => 'This field allows <a href="https://help.github.com/articles/github-flavored-markdown/">Github flavored markdown</a>.',
'min_amt' => 'Min. QTY',
'min_amt_help' => 'Minimum number of items that should be available before an alert gets triggered.',
'min_amt_help' => 'Minimum number of items that should be available before an alert gets triggered. Leave Min. QTY blank if you do not want to receive alerts for low inventory.',
'model_no' => 'Model No.',
'months' => 'months',
'moreinfo' => 'More Info',

View file

@ -64,6 +64,7 @@ return [
'string' => 'The :attribute must be at least :min characters.',
'array' => 'The :attribute must have at least :min items.',
],
'starts_with' => 'The :attribute must start with one of the following: :values.',
'not_in' => 'The selected :attribute is invalid.',
'numeric' => 'The :attribute must be a number.',
'present' => 'The :attribute field must be present.',

View file

@ -64,7 +64,7 @@
@if ($snipeSettings->saml_enabled)
<div class="row ">
<div class="col-md-12 text-right">
<div class="text-right col-md-12">
<a href="{{ route('saml.login') }}">{{ trans('auth/general.saml_login') }}</a>
</div>
</div>
@ -73,7 +73,7 @@
<div class="box-footer">
<button class="btn btn-lg btn-primary btn-block">{{ trans('auth/general.login') }}</button>
</div>
<div class="col-md-12 col-sm-12 col-xs-12 text-right" style="padding-top: 10px;">
<div class="text-right col-md-12 col-sm-12 col-xs-12" style="padding-top: 10px;">
@if ($snipeSettings->custom_forgot_pass_url)
<a href="{{ $snipeSettings->custom_forgot_pass_url }}" rel="noopener">{{ trans('auth/general.forgot_password') }}</a>
@else

View file

@ -65,7 +65,7 @@
return newParams;
},
formatLoadingMessage: function () {
return '<h2><i class="fas fa-spinner fa-spin" aria-hidden="true"></i> {{ trans('general.loading_wait') }} </h4>';
return '<h2><i class="fas fa-spinner fa-spin" aria-hidden="true"></i> {{ trans('general.loading') }} </h4>';
},
icons: {
advancedSearchIcon: 'fas fa-search-plus',
@ -638,7 +638,7 @@
decimalfixed = periodless.replace(/,/g,".");
} else {
// yank commas, that's it.
decimalfixed = number.toString().replace(",","");
decimalfixed = number.toString().replace(/\,/g,"");
}
return parseFloat(decimalfixed);
}
@ -647,14 +647,42 @@
if (Array.isArray(data)) {
var field = this.field;
var total_sum = data.reduce(function(sum, row) {
return (sum) + (cleanFloat(row[field]) || 0);
}, 0);
return numberWithCommas(total_sum.toFixed(2));
}
return 'not an array';
}
function sumFormatterQuantity(data){
if(Array.isArray(data)) {
// Prevents issues on page load where data is an empty array
if(data[0] == undefined){
return 0.00
}
// Check that we are actually trying to sum cost from a table
// that has a quantity column. We must perform this check to
// support licences which use seats instead of qty
if('qty' in data[0]) {
var multiplier = 'qty';
} else if('seats' in data[0]) {
var multiplier = 'seats';
} else {
return 'no quantity';
}
var total_sum = data.reduce(function(sum, row) {
return (sum) + (cleanFloat(row["purchase_cost"])*row[multiplier] || 0);
}, 0);
return numberWithCommas(total_sum.toFixed(2));
}
return 'not an array';
}
function numberWithCommas(value) {
if ((value) && ("{{$snipeSettings->digit_separator}}" == "1.234,56")){
var parts = value.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ".");

View file

@ -235,6 +235,13 @@
</label>
</div>
<div class="checkbox col-md-12">
<label>
{{ Form::checkbox('title', '1', '1', ['class' => 'minimal']) }}
{{ trans('admin/users/table.title') }}
</label>
</div>

View file

@ -195,9 +195,11 @@
if (data.responseJSON) {
var errors = data.responseJSON.message;
var errors = data.responseJSON.errors;
var error_msg = data.responseJSON.message;
} else {
var errors;
var error_msg = 'Something went wrong.';
}
var error_text = '';
@ -205,15 +207,21 @@
$('#save_slack').attr("disabled", true);
$("#slacktesticon").html('');
$("#slackteststatus").addClass('text-danger');
$("#slacktesticon").html('<i class="fas fa-exclamation-triangle text-danger"></i>');
$("#slacktesticon").html('<i class="fas fa-exclamation-triangle text-danger"></i><span class="text-danger">' + error_msg+ '</span>');
if (data.status == 500) {
$('#slackteststatus').html('{{ trans('admin/settings/message.slack.500') }}');
} else if (data.status == 400) {
} else if ((data.status == 400) || (data.status == 422)) {
// TODO: Needs translation
console.log('Type of errors is '+ typeof errors);
console.log('Data status was 400 or 422');
if (typeof errors != 'string') {
console.log(errors.length);
for (i = 0; i < errors.length; i++) {
for (i in errors) {
if (errors[i]) {
error_text += '<li>Error: ' + errors[i];
}
@ -221,6 +229,7 @@
}
} else {
error_text = errors;
}

View file

@ -0,0 +1,51 @@
<?php
namespace Tests\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
class LoginTest extends DuskTestCase
{
/**
* Test login
*
* @return void
*/
public function testLoginPageLoadsAndUserCanLogin()
{
$this->browse(function (Browser $browser) {
$browser->visitRoute('login')
->assertSee(trans('auth/general.login_prompt'));
});
$this->browse(function ($browser) {
$browser->visitRoute('login')
->type('username', 'snipe')
->type('password', 'password')
->press(trans('auth/general.login'))
->assertPathIs('/');
$browser->screenshot('dashboard');
});
}
/**
* Test dashboard loads
*
* @todo Flesh this out further to make sure the individual tables actually load with
* content inside them.
*
* @return void
*/
public function testDashboardLoadsWithSuperAdmin()
{
$this->browse(function ($browser) {
$browser->assertSee(trans('general.dashboard'));
$browser->assertSee(trans('general.loading'));
$browser->screenshot('dashboard-2');
});
}
}

View file

@ -0,0 +1,41 @@
<?php
namespace Tests\Browser\Pages;
use Laravel\Dusk\Browser;
class HomePage extends Page
{
/**
* Get the URL for the page.
*
* @return string
*/
public function url()
{
return '/';
}
/**
* Assert that the browser is on the page.
*
* @param \Laravel\Dusk\Browser $browser
* @return void
*/
public function assert(Browser $browser)
{
//
}
/**
* Get the element shortcuts for the page.
*
* @return array
*/
public function elements()
{
return [
'@element' => '#selector',
];
}
}

View file

@ -0,0 +1,20 @@
<?php
namespace Tests\Browser\Pages;
use Laravel\Dusk\Page as BasePage;
abstract class Page extends BasePage
{
/**
* Get the global element shortcuts for the site.
*
* @return array
*/
public static function siteElements()
{
return [
'@element' => '#selector',
];
}
}

2
tests/Browser/console/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*
!.gitignore

2
tests/Browser/screenshots/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*
!.gitignore

2
tests/Browser/source/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*
!.gitignore

View file

@ -0,0 +1,22 @@
<?php
namespace Tests;
use Illuminate\Contracts\Console\Kernel;
trait CreatesApplication
{
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication()
{
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
return $app;
}
}

61
tests/DuskTestCase.php Normal file
View file

@ -0,0 +1,61 @@
<?php
namespace Tests;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Laravel\Dusk\TestCase as BaseTestCase;
abstract class DuskTestCase extends BaseTestCase
{
use CreatesApplication;
/**
* Prepare for Dusk test execution.
*
* @beforeClass
* @return void
*/
public static function prepare()
{
if (! static::runningInSail()) {
static::startChromeDriver();
}
}
/**
* Create the RemoteWebDriver instance.
*
* @return \Facebook\WebDriver\Remote\RemoteWebDriver
*/
protected function driver()
{
$options = (new ChromeOptions)->addArguments(collect([
'--window-size=1920,1080',
])->unless($this->hasHeadlessDisabled(), function ($items) {
return $items->merge([
'--disable-gpu',
'--headless',
]);
})->all());
return RemoteWebDriver::create(
$_ENV['DUSK_DRIVER_URL'] ?? 'http://localhost:9515',
DesiredCapabilities::chrome()->setCapability(
ChromeOptions::CAPABILITY, $options
)
);
}
/**
* Determine whether the Dusk command has disabled headless mode.
*
* @return bool
*/
protected function hasHeadlessDisabled()
{
return isset($_SERVER['DUSK_HEADLESS_DISABLED']) ||
isset($_ENV['DUSK_HEADLESS_DISABLED']);
}
}

View file

@ -1,3 +0,0 @@
* Dump should contain at least one category of each type for functional testing.
* acceptance: replace some amonpage with checking url after clicking create
* acceptance: asset model test

View file

@ -1,35 +1,10 @@
<?php
class TestCase extends Illuminate\Foundation\Testing\TestCase
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
/**
* The base URL to use while testing the application.
*
* @var string
*/
protected $baseUrl = 'http://localhost:8000';
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication()
{
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
return $app;
}
protected function setUp(): void
{
parent::setUp();
}
protected function tearDown(): void
{
//Artisan::call('migrate:reset');
parent::tearDown();
}
use CreatesApplication;
}

View file

@ -0,0 +1,69 @@
<?php
namespace Tests\Unit;
use App\Models\Accessory;
use App\Models\Manufacturer;
use App\Models\Location;
use App\Models\Category;
use App\Models\Company;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\Unit\BaseTest;
class AccessoryTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testAnAccessoryBelongsToACompany()
{
$accessory = Accessory::factory()
->create(
[
'company_id' =>
Company::factory()->create()->id]);
$this->assertInstanceOf(Company::class, $accessory->company);
}
public function testAnAccessoryHasALocation()
{
$accessory = Accessory::factory()
->create(
[
'location_id' => Location::factory()->create()->id
]);
$this->assertInstanceOf(Location::class, $accessory->location);
}
public function testAnAccessoryBelongsToACategory()
{
$accessory = Accessory::factory()->appleBtKeyboard()
->create(
[
'category_id' =>
Category::factory()->create(
[
'category_type' => 'accessory'
]
)->id]);
$this->assertInstanceOf(Category::class, $accessory->category);
$this->assertEquals('accessory', $accessory->category->category_type);
}
public function testAnAccessoryHasAManufacturer()
{
$this->createValidManufacturer('apple');
$this->createValidCategory('accessory-keyboard-category');
$accessory = Accessory::factory()->appleBtKeyboard()->create(
[
'category_id' => Category::factory()->create(),
'category_id' => Manufacturer::factory()->apple()->create()
]);
$this->assertInstanceOf(Manufacturer::class, $accessory->manufacturer);
}
}

View file

@ -1,6 +1,9 @@
<?php
namespace Tests\Unit;
use App\Models\AssetMaintenance;
use Tests\Unit\BaseTest;
use Carbon\Carbon;
class AssetMaintenanceTest extends BaseTest
{

View file

@ -0,0 +1,47 @@
<?php
namespace Tests\Unit;
use App\Models\Asset;
use App\Models\Category;
use App\Models\AssetModel;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\Unit\BaseTest;
class AssetModelTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testAnAssetModelZerosOutBlankEols()
{
$am = new AssetModel;
$am->eol = '';
$this->assertTrue($am->eol === 0);
$am->eol = '4';
$this->assertTrue($am->eol == 4);
}
public function testAnAssetModelContainsAssets()
{
$category = Category::factory()->create(
['category_type' => 'asset']
);
$model = AssetModel::factory()->create([
'category_id' => $category->id,
]);
$asset = Asset::factory()
->create(
[
'model_id' => $model->id
]
);
$this->assertEquals(1, $model->assets()->count());
}
}

70
tests/Unit/AssetTest.php Normal file
View file

@ -0,0 +1,70 @@
<?php
namespace Tests\Unit;
use App\Exceptions\CheckoutNotAllowed;
use App\Models\Asset;
use App\Models\AssetModel;
use App\Models\Company;
use App\Models\Location;
use App\Models\User;
use App\Models\Category;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\Unit\BaseTest;
use App\Models\Component;
use App\Models\ActionLog;
class AssetTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
// public function testAutoIncrementMixed()
// {
// $expected = '123411';
// $next = Asset::nextAutoIncrement(
// collect([
// ['asset_tag' => '0012345'],
// ['asset_tag' => 'WTF00134'],
// ['asset_tag' => 'WTF-745'],
// ['asset_tag' => '0012346'],
// ['asset_tag' => '00123410'],
// ['asset_tag' => 'U8T7597h77'],
// ])
// );
// \Log::debug('Next: '.$next);
// $this->assertEquals($expected, $next);
// }
/**
* @test
*/
public function testWarrantyExpiresAttribute()
{
$asset = Asset::factory()
->create(
[
'model_id' => AssetModel::factory()
->create(
[
'category_id' => Category::factory()->assetLaptopCategory()->id
]
)->id,
'warranty_months' => 24,
'purchase_date' => Carbon::createFromDate(2017, 1, 1)->hour(0)->minute(0)->second(0)
]);
$this->assertEquals(Carbon::createFromDate(2017, 1, 1)->format('Y-m-d'), $asset->purchase_date->format('Y-m-d'));
$this->assertEquals(Carbon::createFromDate(2019, 1, 1)->format('Y-m-d'), $asset->warranty_expires->format('Y-m-d'));
}
}

View file

@ -1,18 +1,23 @@
<?php
namespace Tests\Unit;
use App\Models\User;
use App\Models\Setting;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\TestCase;
use Auth;
use Artisan;
class BaseTest extends \Codeception\TestCase\Test
class BaseTest extends TestCase
{
use DatabaseTransactions;
protected function _before()
{
Artisan::call('migrate');
\App\Models\Setting::factory()->create();
Setting::factory()->create();
}
protected function signIn($user = null)
@ -23,39 +28,38 @@ class BaseTest extends \Codeception\TestCase\Test
]);
}
Auth::login($user);
return $user;
}
protected function createValidAssetModel($state = 'mbp-13-model', $overrides = [])
protected function createValidAssetModel()
{
return \App\Models\AssetModel::factory()->state()->create(array_merge([
return \App\Models\AssetModel::factory()->create([
'category_id' => $this->createValidCategory(),
'manufacturer_id' => $this->createValidManufacturer(),
'depreciation_id' => $this->createValidDepreciation(),
], $overrides));
]);
}
protected function createValidCategory($state = 'asset-laptop-category', $overrides = [])
protected function createValidCategory()
{
return \App\Models\Category::factory()->state()->create($overrides);
return \App\Models\Category::factory()->make();
}
protected function createValidCompany($overrides = [])
protected function createValidCompany()
{
return \App\Models\Company::factory()->create($overrides);
return \App\Models\Company::factory()->create();
}
protected function createValidDepartment($state = 'engineering', $overrides = [])
{
return \App\Models\Department::factory()->state()->create(array_merge([
return \App\Models\Department::factory()->create(array_merge([
'location_id' => $this->createValidLocation()->id,
], $overrides));
}
protected function createValidDepreciation($state = 'computer', $overrides = [])
protected function createValidDepreciation()
{
return \App\Models\Depreciation::factory()->state()->create($overrides);
return \App\Models\Depreciation::factory()->create();
}
protected function createValidLocation($overrides = [])
@ -63,9 +67,9 @@ class BaseTest extends \Codeception\TestCase\Test
return \App\Models\Location::factory()->create($overrides);
}
protected function createValidManufacturer($state = 'apple', $overrides = [])
protected function createValidManufacturer()
{
return \App\Models\Manufacturer::factory()->state()->create($overrides);
return \App\Models\Manufacturer::factory()->create();
}
protected function createValidSupplier($overrides = [])

View file

@ -0,0 +1,99 @@
<?php
namespace Tests\Unit;
use App\Models\Category;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\Unit\BaseTest;
use App\Models\AssetModel;
use App\Models\Asset;
use App\Models\Accessory;
class CategoryTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testFailsEmptyValidation()
{
// An Asset requires a name, a qty, and a category_id.
$a = Category::create();
$this->assertFalse($a->isValid());
$fields = [
'name' => 'name',
'category_type' => 'category type',
];
$errors = $a->getErrors();
foreach ($fields as $field => $fieldTitle) {
$this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required.");
}
}
public function testACategoryCanHaveAssets()
{
$category = Category::factory()->assetDesktopCategory();
// Generate 5 models via factory
$models = AssetModel::factory()
->mbp13Model()
->count(5)
->create(
[
'category_id' => $category->id
]
);
// Loop through the models and create 2 assets in each model
$models->each(function ($model) {
//dd($model);
$asset = Asset::factory()
->count(2)
->create(
[
'model_id' => $model->id,
]
);
//dd($asset);
});
$this->assertCount(5, $category->models);
$this->assertCount(5, $category->models);
$this->assertEquals(10, $category->itemCount());
}
// public function testACategoryCanHaveAccessories()
// {
// $category = Category::factory()->assetDesktopCategory()->create();
// Accessory::factory()->count(5)->appleBtKeyboard()->create(
// [
// 'category_id' => $category->id
// ]
// );
// $this->assertCount(5, $category->accessories);
// $this->assertEquals(5, $category->itemCount());
// }
// public function testACategoryCanHaveConsumables()
// {
// $category = $this->createValidCategory('consumable-paper-category');
// \App\Models\Consumable::factory()->count(5)->cardstock()->create(['category_id' => $category->id]);
// $this->assertCount(5, $category->consumables);
// $this->assertEquals(5, $category->itemCount());
// }
// public function testACategoryCanHaveComponents()
// {
// $category = $this->createValidCategory('component-ram-category');
// \App\Models\Component::factory()->count(5)->ramCrucial4()->create(['category_id' => $category->id]);
// $this->assertCount(5, $category->components);
// $this->assertEquals(5, $category->itemCount());
// }
}

View file

@ -0,0 +1,34 @@
<?php
namespace Tests\Unit;
use App\Models\Company;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\Unit\BaseTest;
use App\Models\Component;
use App\Models\Asset;
use App\Models\Consumable;
use App\Models\User;
class CompanyTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testACompanyCanHaveUsers()
{
$company = Company::factory()->create();
$user = User::factory()
->create(
[
'company_id'=> $company->id
]
);
$this->assertCount(1, $company->users);
}
}

View file

@ -0,0 +1,54 @@
<?php
namespace Tests\Unit;
use App\Models\Category;
use App\Models\Company;
use App\Models\Component;
use App\Models\Location;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\Unit\BaseTest;
class ComponentTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testAComponentBelongsToACompany()
{
$component = Component::factory()
->create(
[
'company_id' => Company::factory()->create()->id
]
);
$this->assertInstanceOf(Company::class, $component->company);
}
public function testAComponentHasALocation()
{
$component = Component::factory()
->create(['location_id' => Location::factory()->create()->id]);
$this->assertInstanceOf(Location::class, $component->location);
}
public function testAComponentBelongsToACategory()
{
$component = Component::factory()->ramCrucial4()
->create(
[
'category_id' =>
Category::factory()->create(
[
'category_type' => 'component'
]
)->id]);
$this->assertInstanceOf(Category::class, $component->category);
$this->assertEquals('component', $component->category->category_type);
}
}

View file

@ -0,0 +1,19 @@
<?php
namespace Tests\Unit;
use App\Models\Consumable;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\Unit\BaseTest;
class ConsumableTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
}

View file

@ -1,10 +1,11 @@
<?php
namespace Tests\Unit;
use App\Models\CustomField;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Hash;
use Tests\Unit\BaseTest;
/*
* Test strings for db column names gathered from

View file

@ -0,0 +1,52 @@
<?php
namespace Tests\Unit;
use App\Models\Depreciation;
use Tests\Unit\BaseTest;
use App\Models\Category;
use App\Models\License;
use App\Models\AssetModel;
class DepreciationTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testADepreciationHasModels()
{
$this->createValidAssetModel();
$depreciation = Depreciation::factory()->create();
AssetModel::factory()
->mbp13Model()
->count(5)
->create(
[
'category_id' => Category::factory()->assetLaptopCategory(),
'depreciation_id' => $depreciation->id
]);
$this->assertEquals(5, $depreciation->models->count());
}
public function testADepreciationHasLicenses()
{
$depreciation = Depreciation::factory()->create();
License::factory()
->count(5)
->photoshop()
->create(
[
'category_id' => Category::factory()->licenseGraphicsCategory(),
'depreciation_id' => $depreciation->id
]);
$this->assertEquals(5, $depreciation->licenses()->count());
}
}

747
tests/Unit/ImporterTest.php Normal file
View file

@ -0,0 +1,747 @@
<?php
namespace Tests\Unit;
use App\Importer\AccessoryImporter;
use App\Importer\AssetImporter;
use App\Importer\ConsumableImporter;
use App\Importer\LicenseImporter;
use App\Importer\UserImporter;
use App\Models\Accessory;
use App\Models\Asset;
use App\Models\AssetModel;
use App\Models\Category;
use App\Models\CustomField;
use App\Models\Location;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Notification;
use Tests\Unit\BaseTest;
class ImporterTest extends BaseTest
{
/**
* @var \UnitTester
*/
// protected $tester;
// public function testDefaultImportAssetWithCustomFields()
// {
// $this->signIn();
// $csv = <<<'EOT'
// Full Name,Email,Username,item Name,Category,Model name,Manufacturer,Model Number,Serial,Asset Tag,Location,Notes,Purchase Date,Purchase Cost,Company,Status,Warranty,Supplier,Weight
// Bonnie Nelson,bnelson0@cdbaby.com,bnelson0,eget nunc donec quis,quam,massa id,Linkbridge,6377018600094472,27aa8378-b0f4-4289-84a4-405da95c6147,970882174-8,Daping,"Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.",2016-04-05,133289.59,Alpha,Undeployable,14,Blogspan,35
// EOT;
// $this->initializeCustomFields();
// $this->import(new AssetImporter($csv));
// $this->tester->seeRecord('users', [
// 'first_name' => 'Bonnie',
// 'last_name' => 'Nelson',
// 'email' => 'bnelson0@cdbaby.com',
// ]);
// $this->tester->seeRecord('categories', [
// 'name' => 'quam',
// ]);
// $this->tester->seeRecord('models', [
// 'name' => 'massa id',
// 'model_number' => 6377018600094472,
// ]);
// $this->tester->seeRecord('manufacturers', [
// 'name' => 'Linkbridge',
// ]);
// $this->tester->seeRecord('locations', [
// 'name' => 'Daping',
// ]);
// $this->tester->seeRecord('companies', [
// 'name' => 'Alpha',
// ]);
// $this->tester->seeRecord('status_labels', [
// 'name' => 'Undeployable',
// ]);
// $this->tester->seeRecord('suppliers', [
// 'name' => 'Blogspan',
// ]);
// $this->tester->seeRecord('assets', [
// 'name' => 'eget nunc donec quis',
// 'serial' => '27aa8378-b0f4-4289-84a4-405da95c6147',
// 'asset_tag' => '970882174-8',
// 'notes' => 'Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.',
// 'purchase_date' => '2016-04-05 00:00:01',
// 'purchase_cost' => 133289.59, 'warranty_months' => 14,
// '_snipeit_weight_2' => 35,
// ]);
// }
// public function testImportCheckoutToLocation()
// {
// $this->signIn();
// // Testing in order:
// // * Asset to user, no checkout type defined (default to user).
// // * Asset to user, explicit user checkout type (Checkout to user)
// // * Asset to location, location does not exist to begin with
// // * Asset to preexisting location.
// $csv = <<<'EOT'
// Full Name,Email,Username,Checkout Location,Checkout Type,item Name,Category,Model name,Manufacturer,Model Number,Serial,Asset Tag,Location,Notes,Purchase Date,Purchase Cost,Company,Status,Warranty,Supplier,Weight
// Bonnie Nelson,bnelson0@cdbaby.com,bnelson0,,,eget nunc donec quis,quam,massa id,Linkbridge,6377018600094472,27aa8378-b0f4-4289-84a4-405da95c6147,970882174-8,Daping,"Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.",2016-04-05,133289.59,Alpha,Undeployable,14,Blogspan,35
// Mildred Gibson,mgibson2@wiley.com,mgibson2,,user,morbi quis tortor id,nunc nisl duis,convallis tortor risus,Lajo,374622546776765,2837ab20-8f0d-4935-8a52-226392f2b1b0,710141467-2,Shekou,In congue. Etiam justo. Etiam pretium iaculis justo.,2015-08-09,233.57,Konklab,Lost,,,
// ,,,Planet Earth,location,dictumst maecenas ut,sem praesent,accumsan felis,Layo,30052522651756,4751495c-cee0-4961-b788-94a545b5643e,998233705-X,Dante Delgado,,2016-04-16,261.79,,Archived,15,Ntag,
// ,,,Daping,location,viverra diam vitae,semper sapien,dapibus dolor vel,Flashset,3559785746335392,e287bb64-ff4f-434c-88ab-210ad433c77b,927820758-6,Achiaman,,2016-03-05,675.3,,Archived,22,Meevee,
// EOT;
// $this->import(new AssetImporter($csv));
// $user = User::where('username', 'bnelson0')->firstOrFail();
// $this->tester->seeRecord('assets', [
// 'asset_tag' => '970882174-8',
// 'assigned_type' => User::class,
// 'assigned_to' => $user->id,
// ]);
// $user = User::where('username', 'mgibson2')->firstOrFail();
// $this->tester->seeRecord('assets', [
// 'asset_tag' => '710141467-2',
// 'assigned_type' => User::class,
// 'assigned_to' => $user->id,
// ]);
// $location = Location::where('name', 'Planet Earth')->firstOrFail();
// $this->tester->seeRecord('assets', [
// 'asset_tag' => '998233705-X',
// 'assigned_type' => Location::class,
// 'assigned_to' => $location->id,
// ]);
// $location = Location::where('name', 'Daping')->firstOrFail();
// $this->tester->seeRecord('assets', [
// 'asset_tag' => '927820758-6',
// 'assigned_type' => Location::class,
// 'assigned_to' => $location->id,
// ]);
// }
// public function testUpdateAssetIncludingCustomFields()
// {
// $this->signIn();
// $csv = <<<'EOT'
// Name,Email,Username,item Name,Category,Model name,Manufacturer,Model Number,Serial,Asset Tag,Location,Notes,Purchase Date,Purchase Cost,Company,Status,Warranty,Supplier,weight
// Bonnie Nelson,bnelson0@cdbaby.com,bnelson0,eget nunc donec quis,quam,massa id,Linkbridge,6377018600094472,27aa8378-b0f4-4289-84a4-405da95c6147,970882174-8,Daping,"Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.",2016-04-05,133289.59,Alpha,Undeployable,14,Blogspan,95
// EOT;
// $this->initializeCustomFields();
// $this->import(new AssetImporter($csv));
// $updatedCSV = <<<'EOT'
// item Name,Category,Model name,Manufacturer,Model Number,Serial,Asset Tag,Location,Notes,Purchase Date,Purchase Cost,Company,Status,Warranty,Supplier
// A new name,some other category,Another Model,Linkbridge 32,356,67433477,970882174-8,New Location,I have no notes,2018-04-05,25.59,Another Company,Ready To Go,18,Not Creative
// EOT;
// $importer = new AssetImporter($updatedCSV);
// $importer->setUserId(1)
// ->setUpdating(true)
// ->setUsernameFormat('firstname.lastname')
// ->import();
// $this->tester->seeRecord('categories', [
// 'name' => 'some other category',
// ]);
// $this->tester->seeRecord('models', [
// 'name' => 'Another Model',
// 'model_number' => 356,
// ]);
// $this->tester->seeRecord('manufacturers', [
// 'name' => 'Linkbridge 32',
// ]);
// $this->tester->seeRecord('locations', [
// 'name' => 'New Location',
// ]);
// $this->tester->seeRecord('companies', [
// 'name' => 'Another Company',
// ]);
// $this->tester->seeRecord('status_labels', [
// 'name' => 'Ready To Go',
// ]);
// $this->tester->seeRecord('suppliers', [
// 'name' => 'Not Creative',
// ]);
// $this->tester->seeRecord('assets', [
// 'name' => 'A new name',
// 'serial' => '67433477',
// 'asset_tag' => '970882174-8',
// 'notes' => 'I have no notes',
// 'purchase_date' => '2018-04-05 00:00:01',
// 'purchase_cost' => 25.59,
// 'warranty_months' => 18,
// '_snipeit_weight_2' => 95,
// ]);
// }
// public function testAssetModelNumber4359()
// {
// // As per bug #4359
// // 1) Create model with blank model # and custom field.
// // 2 ) Update custom fields with a csv not including model #
// // 3 ) Not updated. NULL vs. empty issue.
// $this->signIn();
// $csv = <<<'EOT'
// Name,Email,Username,item Name,Category,Model name,Manufacturer,Serial,Asset Tag,Location,Notes,Purchase Date,Purchase Cost,Company,Status,Warranty,Supplier
// Bonnie Nelson,bnelson0@cdbaby.com,bnelson0,eget nunc donec quis,quam,massa id,Linkbridge,27aa8378-b0f4-4289-84a4-405da95c6147,970882174-8,Daping,"Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.",2016-04-05,133289.59,Alpha,Undeployable,14,Blogspan
// EOT;
// // Need to do this manually...
// $customField = \App\Models\CustomField::factory()->create(['name' => 'Weight']);
// $customFieldSet = \App\Models\CustomFieldset::factory()->create(['name' => 'Default']);
// $customFieldSet->fields()->attach($customField, [
// 'required' => false,
// 'order' => 'asc', ]);
// \App\Models\Category::factory()->assetLaptopCategory()->create([
// 'name' => 'quam',
// ]);
// \App\Models\Manufacturer::factory()->apple()->create([
// 'name' => 'Linkbridge',
// ]);
// $am = \App\Models\AssetModel::factory()->create([
// 'name' => 'massa id',
// 'fieldset_id' => $customFieldSet->id,
// 'category_id' => 1,
// 'manufacturer_id' => 1,
// 'model_number' => null,
// ]);
// $this->import(new AssetImporter($csv));
// $updatedCSV = <<<'EOT'
// Serial,Asset Tag,weight
// 67433477,970882174-8,115
// EOT;
// $importer = new AssetImporter($updatedCSV);
// $importer->setUserId(1)
// ->setUpdating(true)
// ->setUsernameFormat('firstname.lastname')
// ->import();
// $this->tester->seeRecord('assets', [
// 'asset_tag' => '970882174-8',
// '_snipeit_weight_2' => 115,
// ]);
// }
// public function initializeCustomFields()
// {
// $customField = \App\Models\CustomField::factory()->create(['name' => 'Weight']);
// $customFieldSet = \App\Models\CustomFieldset::factory()->create(['name' => 'Default']);
// $customFieldSet->fields()->attach($customField, [
// 'required' => false,
// 'order' => 'asc', ]);
// $am = \App\Models\AssetModel::factory()->create([
// 'name' => 'massa id',
// 'fieldset_id' => $customFieldSet->id,
// ]);
// }
// public function testCustomMappingImport()
// {
// $this->signIn();
// $csv = <<<'EOT'
// Full Name,Email,Username,object name,Cat,Model name,Manufacturer,Model Number,Serial,Asset,Loc,Some Notes,Purchase Date,Purchase Cost,comp,Status,Warranty,Supplier
// Bonnie Nelson,bnelson0@cdbaby.com,bnelson0,eget nunc donec quis,quam,massa id,Linkbridge,6377018600094472,27aa8378-b0f4-4289-84a4-405da95c6147,970882174-8,Daping,"Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.",2016-04-05,133289.59,Alpha,Undeployable,14,Blogspan
// EOT;
// $customFieldMap = [
// 'asset_tag' => 'Asset',
// 'category' => 'Cat',
// 'company' => 'comp',
// 'item_name' => 'object name',
// 'expiration_date' => 'expiration date',
// 'location' => 'loc',
// 'notes' => 'Some Notes',
// 'asset_model' => 'model name',
// ];
// $this->import(new AssetImporter($csv), $customFieldMap);
// // Did we create a user?
// $this->tester->seeRecord('users', [
// 'first_name' => 'Bonnie',
// 'last_name' => 'Nelson',
// 'email' => 'bnelson0@cdbaby.com',
// ]);
// // Grab the user record for use in asserting assigned_to
// $createdUser = $this->tester->grabRecord('users', [
// 'first_name' => 'Bonnie',
// 'last_name' => 'Nelson',
// 'email' => 'bnelson0@cdbaby.com',
// ]);
// $this->tester->seeRecord('categories', [
// 'name' => 'quam',
// ]);
// $this->tester->seeRecord('models', [
// 'name' => 'massa id',
// 'model_number' => 6377018600094472,
// ]);
// $this->tester->seeRecord('manufacturers', [
// 'name' => 'Linkbridge',
// ]);
// $this->tester->seeRecord('locations', [
// 'name' => 'Daping',
// ]);
// $this->tester->seeRecord('companies', [
// 'name' => 'Alpha',
// ]);
// $this->tester->seeRecord('status_labels', [
// 'name' => 'Undeployable',
// ]);
// $this->tester->seeRecord('suppliers', [
// 'name' => 'Blogspan',
// ]);
// $this->tester->seeRecord('assets', [
// 'name' => 'eget nunc donec quis',
// 'serial' => '27aa8378-b0f4-4289-84a4-405da95c6147',
// 'asset_tag' => '970882174-8',
// 'notes' => 'Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.',
// 'purchase_date' => '2016-04-05 00:00:01',
// 'purchase_cost' => 133289.59,
// 'warranty_months' => 14,
// 'assigned_to' => $createdUser['id'],
// 'assigned_type' => User::class,
// ]);
// }
// public function testDefaultAccessoryImport()
// {
// $csv = <<<'EOT'
// Item Name,Purchase Date,Purchase Cost,Location,Company,Order Number,Category,Requestable,Quantity
// Walter Carter,09/01/2006,,metus. Vivamus,Macromedia,J935H60W,Customers,False,278
// EOT;
// $this->import(new AccessoryImporter($csv));
// $this->tester->seeRecord('accessories', [
// 'name' => 'Walter Carter',
// 'purchase_date' => '2006-09-01 00:00:01',
// 'order_number' => 'J935H60W',
// 'requestable' => 0,
// 'qty' => 278,
// ]);
// $this->tester->seeRecord('locations', [
// 'name' => 'metus. Vivamus',
// ]);
// $this->tester->seeRecord('companies', [
// 'name' => 'Macromedia',
// ]);
// $this->tester->seeRecord('categories', [
// 'name' => 'Customers',
// ]);
// }
// public function testDefaultAccessoryUpdate()
// {
// $csv = <<<'EOT'
// Item Name,Purchase Date,Purchase Cost,Location,Company,Order Number,Category,Requestable,Quantity
// Walter Carter,09/01/2006,,metus. Vivamus,Macromedia,J935H60W,Customers,False,278
// EOT;
// $this->import(new AccessoryImporter($csv));
// $this->tester->seeNumRecords(1, 'accessories');
// $updatedCSV = <<<'EOT'
// Item Name,Purchase Date,Purchase Cost,Location,Company,Order Number,Category,Requestable,Quantity
// Walter Carter,09/01/2015,350,metus. Vivamus,Macromedia,35GGH,Customers,True,12
// EOT;
// $importer = new AccessoryImporter($updatedCSV);
// $importer->setUserId(1)
// ->setUpdating(true)
// ->import();
// // At this point we should still only have one record.
// $this->tester->seeNumRecords(1, 'accessories');
// // But instead these.
// $this->tester->seeRecord('accessories', [
// 'name' => 'Walter Carter',
// 'purchase_date' => '2015-09-01 00:00:01',
// 'order_number' => '35GGH',
// 'requestable' => 1,
// 'qty' => 12,
// ]);
// }
// public function testCustomAccessoryImport()
// {
// $csv = <<<'EOT'
// Name,Pur Date,Cost,Loc,Comp,Order Num,Cat,Request,Quan
// Walter Carter,09/01/2006,,metus. Vivamus,Macromedia,J935H60W,Customers,False,278
// EOT;
// $customFieldMap = [
// 'category' => 'Cat',
// 'company' => 'Comp',
// 'item_name' => 'Name',
// 'location' => 'Loc',
// 'purchase_date' => 'Pur Date',
// 'purchase_cost' => 'Cost',
// 'order_number' => 'Order Num',
// 'requestable' => 'Request',
// 'quantity' => 'Quan',
// ];
// $this->import(new AccessoryImporter($csv), $customFieldMap);
// // dd($this->tester->grabRecord('accessories'));
// $this->tester->seeRecord('accessories', [
// 'name' => 'Walter Carter',
// 'purchase_date' => '2006-09-01 00:00:01',
// 'order_number' => 'J935H60W',
// 'requestable' => 0,
// 'qty' => 278,
// ]);
// $this->tester->seeRecord('locations', [
// 'name' => 'metus. Vivamus',
// ]);
// $this->tester->seeRecord('companies', [
// 'name' => 'Macromedia',
// ]);
// $this->tester->seeRecord('categories', [
// 'name' => 'Customers',
// ]);
// }
// public function testDefaultConsumableImport()
// {
// $csv = <<<'EOT'
// Item Name,Purchase Date,Purchase Cost,Location,Company,Order Number,Category,Requestable,Quantity,Item Number,Model Number
// eget,01/03/2011,$85.91,mauris blandit mattis.,Lycos,T295T06V,Triamterene/Hydrochlorothiazide,No,322,3305,30123
// EOT;
// $this->import(new ConsumableImporter($csv));
// $this->tester->seeRecord('consumables', [
// 'name' => 'eget',
// 'purchase_date' => '2011-01-03 00:00:01',
// 'purchase_cost' => 85.91,
// 'order_number' => 'T295T06V',
// 'requestable' => 0,
// 'qty' => 322,
// 'item_no' => 3305,
// 'model_number' => 30123,
// ]);
// $this->tester->seeRecord('locations', [
// 'name' => 'mauris blandit mattis.',
// ]);
// $this->tester->seeRecord('companies', [
// 'name' => 'Lycos',
// ]);
// $this->tester->seeRecord('categories', [
// 'name' => 'Triamterene/Hydrochlorothiazide',
// ]);
// }
// public function testDefaultConsumableUpdate()
// {
// $csv = <<<'EOT'
// Item Name,Purchase Date,Purchase Cost,Location,Company,Order Number,Category,Requestable,Quantity
// eget,01/03/2011,85.91,mauris blandit mattis.,Lycos,T295T06V,Triamterene/Hydrochlorothiazide,No,322
// EOT;
// $this->import(new ConsumableImporter($csv));
// $this->tester->seeNumRecords(1, 'consumables');
// $updatedCSV = <<<'EOT'
// Item Name,Purchase Date,Purchase Cost,Location,Company,Order Number,Category,Requestable,Quantity
// eget,12/05/2016,35.45,mauris blandit mattis.,Lycos,3666FF,New Cat,Yes,15
// EOT;
// $importer = new ConsumableImporter($updatedCSV);
// $importer->setUserId(1)
// ->setUpdating(true)
// ->import();
// // At this point we should still only have one record.
// $this->tester->seeNumRecords(1, 'consumables');
// // But instead these.
// $this->tester->seeRecord('consumables', [
// 'name' => 'eget',
// 'purchase_date' => '2016-12-05 00:00:01',
// 'purchase_cost' => 35.45,
// 'order_number' => '3666FF',
// 'requestable' => 1,
// 'qty' => 15,
// ]);
// }
// public function testCustomConsumableImport()
// {
// $csv = <<<'EOT'
// Name,pur Date,Pur Cost,Loc,Comp,Order Num,Kat,Request,Quan
// eget,01/03/2011,85.91,mauris blandit mattis.,Lycos,T295T06V,Triamterene/Hydrochlorothiazide,No,322
// EOT;
// $customFieldMap = [
// 'category' => 'Kat',
// 'company' => 'Comp',
// 'item_name' => 'Name',
// 'location' => 'Loc',
// 'purchase_date' => 'Pur date',
// 'purchase_cost' => 'Pur Cost',
// 'order_number' => 'Order Num',
// 'requestable' => 'Request',
// 'quantity' => 'Quan',
// ];
// $this->import(new ConsumableImporter($csv), $customFieldMap);
// $this->tester->seeRecord('consumables', [
// 'name' => 'eget',
// 'purchase_date' => '2011-01-03 00:00:01',
// 'purchase_cost' => 85.91,
// 'order_number' => 'T295T06V',
// 'requestable' => 0,
// 'qty' => 322,
// ]);
// $this->tester->seeRecord('locations', [
// 'name' => 'mauris blandit mattis.',
// ]);
// $this->tester->seeRecord('companies', [
// 'name' => 'Lycos',
// ]);
// $this->tester->seeRecord('categories', [
// 'name' => 'Triamterene/Hydrochlorothiazide',
// ]);
// }
// public function testDefaultLicenseImport()
// {
// $this->signIn();
// $csv = <<<'EOT'
// Full Name,Email,Username,Item name,serial,manufacturer,purchase date,purchase cost,purchase order,order number,Licensed To Name,Licensed to Email,expiration date,maintained,reassignable,seats,company,supplier,category,notes,asset tag
// Helen Anderson,cspencer0@privacy.gov.au,cspencer0,Argentum Malachite Athletes Foot Relief,1aa5b0eb-79c5-40b2-8943-5472a6893c3c,"Beer, Leannon and Lubowitz",07/13/2012,$79.66,53008,386436062-5,Cynthia Spencer,cspencer0@gov.uk,01/27/2016,false,no,80,"Haag, Schmidt and Farrell","Hegmann, Mohr and Cremin",Graphics Software,Sed ante. Vivamus tortor. Duis mattis egestas metus.,test 1
// EOT;
// // Force create an asset to match the checkout
// $testAsset = $this->createValidAsset(['asset_tag' => 'test 1']);
// $this->import(new LicenseImporter($csv));
// // dd($this->tester->grabRecord('licenses'));
// // Did we create a user?
// $this->tester->seeRecord('users', [
// 'first_name' => 'Helen',
// 'last_name' => 'Anderson',
// 'email' => 'cspencer0@privacy.gov.au',
// ]);
// // Grab the user record for use in asserting assigned_to
// $createdUser = $this->tester->grabRecord('users', [
// 'first_name' => 'Helen',
// 'last_name' => 'Anderson',
// 'email' => 'cspencer0@privacy.gov.au',
// ]);
// $this->tester->seeRecord('licenses', [
// 'name' => 'Argentum Malachite Athletes Foot Relief',
// 'purchase_date' => '2012-07-13 00:00:01',
// 'seats' => 80,
// 'license_email' => 'cspencer0@gov.uk',
// 'order_number' => '386436062-5',
// 'license_name' => 'Cynthia Spencer',
// 'expiration_date' => '2016-01-27',
// 'maintained' => 0,
// 'notes' => 'Sed ante. Vivamus tortor. Duis mattis egestas metus.',
// 'purchase_cost' => 79.66,
// 'purchase_order' => '53008',
// 'reassignable' => 0,
// 'serial' => '1aa5b0eb-79c5-40b2-8943-5472a6893c3c',
// ]);
// $this->tester->seeRecord('manufacturers', [
// 'name' => 'Beer, Leannon and Lubowitz',
// ]);
// $this->tester->seeRecord('suppliers', [
// 'name' => 'Hegmann, Mohr and Cremin',
// ]);
// $this->tester->seeRecord('companies', [
// 'name' => 'Haag, Schmidt and Farrell',
// ]);
// $this->tester->seeRecord('categories', [
// 'name' => 'Graphics Software',
// ]);
// $this->tester->seeNumRecords(80, 'license_seats');
// $this->tester->seeRecord('license_seats', [
// 'assigned_to' => $createdUser['id'],
// 'license_id' => \App\Models\License::where('serial', '1aa5b0eb-79c5-40b2-8943-5472a6893c3c')->first()->id,
// 'asset_id' => $testAsset->id,
// ]);
// }
// public function testDefaultLicenseUpdate()
// {
// $csv = <<<'EOT'
// Name,Email,Username,Item name,serial,manufacturer,purchase date,purchase cost,purchase order,order number,Licensed To Name,Licensed to Email,expiration date,maintained,reassignable,seats,company,supplier,category,notes
// Helen Anderson,cspencer0@privacy.gov.au,cspencer0,Argentum Malachite Athletes Foot Relief,1aa5b0eb-79c5-40b2-8943-5472a6893c3c,"Beer, Leannon and Lubowitz",07/13/2012,$79.66,53008,386436062-5,Cynthia Spencer,cspencer0@gov.uk,01/27/2016,false,no,80,"Haag, Schmidt and Farrell","Hegmann, Mohr and Cremin",Graphics Software,Sed ante. Vivamus tortor. Duis mattis egestas metus.
// EOT;
// $this->import(new LicenseImporter($csv));
// $this->tester->seeNumRecords(1, 'licenses');
// $updatedCSV = <<<'EOT'
// Item name,serial,manufacturer,purchase date,purchase cost,purchase order,order number,Licensed To Name,Licensed to Email,expiration date,maintained,reassignable,seats,company,supplier,category,notes
// Argentum Malachite Athletes Foot Relief,1aa5b0eb-79c5-40b2-8943-5472a6893c3c,"Beer, Leannon and Lubowitz",05/15/2019,$1865.34,63 ar,18334,A Legend,Legendary@gov.uk,04/27/2016,yes,true,64,"Haag, Schmidt and Farrell","Hegmann, Mohr and Cremin",Graphics Software,Sed ante. Vivamus tortor. Duis mattis egestas metus.
// EOT;
// $importer = new LicenseImporter($updatedCSV);
// $importer->setUserId(1)
// ->setUpdating(true)
// ->import();
// // At this point we should still only have one record.
// $this->tester->seeNumRecords(1, 'licenses');
// // But instead these.
// \Log::debug($this->tester->grabRecord('licenses'));
// $this->tester->seeRecord('licenses', [
// 'name' => 'Argentum Malachite Athletes Foot Relief',
// 'purchase_date' => '2019-05-15 00:00:01',
// 'seats' => 64,
// 'license_email' => 'Legendary@gov.uk',
// 'order_number' => '18334',
// 'license_name' => 'A Legend',
// 'expiration_date' => '2016-04-27',
// 'maintained' => 1,
// 'notes' => 'Sed ante. Vivamus tortor. Duis mattis egestas metus.',
// 'purchase_cost' => 1865.34,
// 'purchase_order' => '63 ar',
// 'reassignable' => 1,
// 'serial' => '1aa5b0eb-79c5-40b2-8943-5472a6893c3c',
// ]);
// // License seats are soft deleted
// $this->tester->seeNumRecords(64, 'license_seats', ['deleted_at' => null]);
// }
// public function testCustomLicenseImport()
// {
// $csv = <<<'EOT'
// Name,Email,Username,Object name,serial num,manuf,pur date,pur cost,purc order,order num,Licensed To,Licensed Email,expire date,maint,reass,seat,comp,supplier,category,note
// Helen Anderson,cspencer0@privacy.gov.au,cspencer0,Argentum Malachite Athletes Foot Relief,1aa5b0eb-79c5-40b2-8943-5472a6893c3c,"Beer, Leannon and Lubowitz",07/13/2012,$79.66,53008,386436062-5,Cynthia Spencer,cspencer0@gov.uk,01/27/2016,false,no,80,"Haag, Schmidt and Farrell","Hegmann, Mohr and Cremin",Custom Graphics Software,Sed ante. Vivamus tortor. Duis mattis egestas metus.
// EOT;
// $customFieldMap = [
// 'company' => 'Comp',
// 'expiration_date' => 'expire date',
// 'item_name' => 'Object Name',
// 'license_email' => 'licensed email',
// 'license_name' => 'licensed to',
// 'maintained' => 'maint',
// 'manufacturer' => 'manuf',
// 'notes' => 'note',
// 'order_number' => 'Order Num',
// 'purchase_cost' => 'Pur Cost',
// 'purchase_date' => 'Pur date',
// 'purchase_order' => 'Purc Order',
// 'quantity' => 'Quan',
// 'reassignable' => 'reass',
// 'requestable' => 'Request',
// 'seats' => 'seat',
// 'serial' => 'serial num',
// 'category' => 'category',
// ];
// $this->import(new LicenseImporter($csv), $customFieldMap);
// $this->tester->seeRecord('licenses', [
// 'name' => 'Argentum Malachite Athletes Foot Relief',
// 'purchase_date' => '2012-07-13 00:00:01',
// 'seats' => 80,
// 'license_email' => 'cspencer0@gov.uk',
// 'order_number' => '386436062-5',
// 'license_name' => 'Cynthia Spencer',
// 'expiration_date' => '2016-01-27',
// 'maintained' => 0,
// 'notes' => 'Sed ante. Vivamus tortor. Duis mattis egestas metus.',
// 'purchase_cost' => 79.66,
// 'purchase_order' => '53008',
// 'reassignable' => 0,
// 'serial' => '1aa5b0eb-79c5-40b2-8943-5472a6893c3c',
// ]);
// $this->tester->seeRecord('manufacturers', [
// 'name' => 'Beer, Leannon and Lubowitz',
// ]);
// $this->tester->seeRecord('suppliers', [
// 'name' => 'Hegmann, Mohr and Cremin',
// ]);
// $this->tester->seeRecord('companies', [
// 'name' => 'Haag, Schmidt and Farrell',
// ]);
// $this->tester->seeNumRecords(80, 'license_seats');
// }
// public function testDefaultUserImport()
// {
// Notification::fake();
// $this->signIn();
// $csv = <<<'EOT'
// First Name,Last Name,email,Username,Location,Phone Number,Job Title,Employee Number,Company,Department,activated
// Blanche,O'Collopy,bocollopy0@livejournal.com,bocollopy0,Hinapalanan,63-(199)661-2186,Clinical Specialist,7080919053,Morar-Ward,Management,1
// Jessie,Primo,,jprimo1,Korenovsk,7-(885)578-0266,Paralegal,6284292031,Jast-Stiedemann,1
// EOT;
// $user_importer = new UserImporter($csv);
// $user_importer->sendWelcome();
// $this->import($user_importer);
// $this->tester->seeRecord('users', [
// 'first_name' => 'Blanche',
// 'last_name' => "O'Collopy",
// 'email' => 'bocollopy0@livejournal.com',
// 'username' => 'bocollopy0',
// 'phone' => '63-(199)661-2186',
// 'jobtitle' => 'Clinical Specialist',
// 'employee_num' => '7080919053',
// ]);
// $this->tester->seeRecord('companies', [
// 'name' => 'Morar-Ward',
// ]);
// $this->tester->seeRecord('departments', [
// 'name' => 'Management',
// ]);
// Notification::assertSentTo(User::find(2), \App\Notifications\WelcomeNotification::class);
// Notification::assertNotSentTo(User::find(3), \App\Notifications\WelcomeNotification::class);
// }
// private function import($importer, $mappings = null)
// {
// if ($mappings) {
// $importer->setFieldMappings($mappings);
// }
// $importer->setUserId(1)
// ->setUpdating(false)
// ->setUsernameFormat('firstname.lastname')
// ->import();
// }
}

View file

@ -1,10 +1,9 @@
<?php
namespace Tests\Unit;
use App\Models\Location;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Hash;
use Tests\Unit\BaseTest;
class LocationTest extends BaseTest
{
@ -35,6 +34,6 @@ class LocationTest extends BaseTest
]);
$this->assertFalse($a->isValid());
$this->assertStringContainsString('The parent id and id must be different', $a->getErrors());
$this->assertStringContainsString(trans('validation.non_circular', ['attribute' => 'parent id']), $a->getErrors());
}
}

View file

@ -0,0 +1,43 @@
<?php
namespace Tests\Unit;
use App\Models\User;
use App\Models\Asset;
use App\Models\AssetModel;
use App\Models\Category;
use Carbon\Carbon;
use App\Notifications\CheckoutAssetNotification;
use Illuminate\Support\Facades\Notification;
use Tests\Unit\BaseTest;
class NotificationTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testAUserIsEmailedIfTheyCheckoutAnAssetWithEULA()
{
$user = User::factory()->create();
$asset = Asset::factory()
->create(
[
'model_id' => AssetModel::factory()
->create(
[
'category_id' => Category::factory()->assetLaptopCategory()->id
]
)->id,
'warranty_months' => 24,
'purchase_date' => Carbon::createFromDate(2017, 1, 1)->hour(0)->minute(0)->second(0)
]);
//dd($asset);
Notification::fake();
$asset->checkOut($user, $asset->id);
Notification::assertSentTo($user, CheckoutAssetNotification::class);
}
}

View file

@ -0,0 +1,513 @@
<?php
namespace Tests\Unit;
use App\Models\Accessory;
use App\Models\Asset;
use App\Models\Component;
use App\Models\Consumable;
use App\Models\License;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\Unit\BaseTest;
class PermissionsTest extends BaseTest
{
// public function _before()
// {
// parent::_before();
// $this->noHardware = [
// 'assets.view' => false,
// 'assets.create' => false,
// 'assets.edit' => false,
// 'assets.delete' => false,
// ];
// $this->noLicenses = [
// 'licenses.view' => false,
// 'licenses.create' => false,
// 'licenses.edit' => false,
// 'licenses.delete' => false,
// ];
// $this->noAccessories = [
// 'accessories.view' => false,
// 'accessories.create' => false,
// 'accessories.edit' => false,
// 'accessories.delete' => false,
// ];
// $this->noConsumables = [
// 'consumables.view' => false,
// 'consumables.create' => false,
// 'consumables.edit' => false,
// 'consumables.delete' => false,
// ];
// $this->noComponents = [
// 'components.view' => false,
// 'components.create' => false,
// 'components.edit' => false,
// 'components.delete' => false,
// ];
// $this->noUsers = [
// 'users.view' => false,
// 'users.create' => false,
// 'users.edit' => false,
// 'users.delete' => false,
// ];
// }
// private $noHardware;
// private $noLicenses;
// private $noAccessories;
// private $noConsumables;
// private $noComponents;
// private $noUsers;
// // tests
// /**
// * @test
// */
// public function a_user_with_no_permissions_sees_nothing()
// {
// $u = \App\Models\User::factory()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
// // $permissions = $this->noHardware;
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_view_asset_permissions_can_view_assets()
// {
// $u = \App\Models\User::factory()->viewAssets()->create();
// $permissions = $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'assets.view' => true,
// 'assets.create' => false,
// 'assets.edit' => false,
// 'assets.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_create_asset_permissions_can_create_assets()
// {
// $u = \App\Models\User::factory()->createAssets()->create();
// $permissions = $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'assets.view' => false,
// 'assets.create' => true,
// 'assets.edit' => false,
// 'assets.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_edit_assets_permissions_can_edit_assets()
// {
// $u = \App\Models\User::factory()->editAssets()->create();
// $permissions = $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'assets.view' => false,
// 'assets.create' => false,
// 'assets.edit' => true,
// 'assets.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_delete_assets_permissions_can_delete_assets()
// {
// $u = \App\Models\User::factory()->deleteAssets()->create();
// $permissions = $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'assets.view' => false,
// 'assets.create' => false,
// 'assets.edit' => false,
// 'assets.delete' => true,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_view_licenses_permissions_can_view_licenses()
// {
// $u = \App\Models\User::factory()->viewLicenses()->create();
// $permissions = $this->noHardware + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'licenses.view' => true,
// 'licenses.create' => false,
// 'licenses.edit' => false,
// 'licenses.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_create_licenses_permissions_can_create_licenses()
// {
// $u = \App\Models\User::factory()->createLicenses()->create();
// $permissions = $this->noHardware + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'licenses.view' => false,
// 'licenses.create' => true,
// 'licenses.edit' => false,
// 'licenses.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_edit_licenses_permissions_can_edit_licenses()
// {
// $u = \App\Models\User::factory()->editLicenses()->create();
// $permissions = $this->noHardware + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'licenses.view' => false,
// 'licenses.create' => false,
// 'licenses.edit' => true,
// 'licenses.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_delete_licenses_permissions_can_delete_licenses()
// {
// $u = \App\Models\User::factory()->deleteLicenses()->create();
// $permissions = $this->noHardware + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'licenses.view' => false,
// 'licenses.create' => false,
// 'licenses.edit' => false,
// 'licenses.delete' => true,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_view_accessories_permissions_can_view_accessories()
// {
// $u = \App\Models\User::factory()->viewAccessories()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noConsumables + $this->noComponents + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'accessories.view' => true,
// 'accessories.create' => false,
// 'accessories.edit' => false,
// 'accessories.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_create_accessories_permissions_can_create_accessories()
// {
// $u = \App\Models\User::factory()->createAccessories()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noConsumables + $this->noComponents + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'accessories.view' => false,
// 'accessories.create' => true,
// 'accessories.edit' => false,
// 'accessories.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_edit_accessories_permissions_can_edit_accessories()
// {
// $u = \App\Models\User::factory()->editAccessories()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noConsumables + $this->noComponents + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'accessories.view' => false,
// 'accessories.create' => false,
// 'accessories.edit' => true,
// 'accessories.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_delete_accessories_permissions_can_delete_accessories()
// {
// $u = \App\Models\User::factory()->deleteAccessories()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noConsumables + $this->noComponents + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'accessories.view' => false,
// 'accessories.create' => false,
// 'accessories.edit' => false,
// 'accessories.delete' => true,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_view_consumables_permissions_can_view_consumables()
// {
// $u = \App\Models\User::factory()->viewConsumables()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noComponents + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'consumables.view' => true,
// 'consumables.create' => false,
// 'consumables.edit' => false,
// 'consumables.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_create_consumables_permissions_can_create_consumables()
// {
// $u = \App\Models\User::factory()->createConsumables()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noConsumables + $this->noComponents + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'consumables.view' => false,
// 'consumables.create' => true,
// 'consumables.edit' => false,
// 'consumables.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_edit_consumables_permissions_can_edit_consumables()
// {
// $u = \App\Models\User::factory()->editConsumables()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noComponents + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'consumables.view' => false,
// 'consumables.create' => false,
// 'consumables.edit' => true,
// 'consumables.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_delete_consumables_permissions_can_delete_consumables()
// {
// $u = \App\Models\User::factory()->deleteConsumables()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noComponents + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'consumables.view' => false,
// 'consumables.create' => false,
// 'consumables.edit' => false,
// 'consumables.delete' => true,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_view_users_permissions_can_view_users()
// {
// $u = \App\Models\User::factory()->viewUsers()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents;
// $permissions = array_merge($permissions, [
// 'users.view' => true,
// 'users.create' => false,
// 'users.edit' => false,
// 'users.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_create_users_permissions_can_create_users()
// {
// $u = \App\Models\User::factory()->createUsers()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents;
// $permissions = array_merge($permissions, [
// 'users.view' => false,
// 'users.create' => true,
// 'users.edit' => false,
// 'users.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_edit_users_permissions_can_edit_users()
// {
// $u = \App\Models\User::factory()->editUsers()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents;
// $permissions = array_merge($permissions, [
// 'users.view' => false,
// 'users.create' => false,
// 'users.edit' => true,
// 'users.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_delete_users_permissions_can_delete_users()
// {
// $u = \App\Models\User::factory()->deleteUsers()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents;
// $permissions = array_merge($permissions, [
// 'users.view' => false,
// 'users.create' => false,
// 'users.edit' => false,
// 'users.delete' => true,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_view_components_permissions_can_view_components()
// {
// $u = \App\Models\User::factory()->viewComponents()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'components.view' => true,
// 'components.create' => false,
// 'components.edit' => false,
// 'components.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_create_components_permissions_can_create_components()
// {
// $u = \App\Models\User::factory()->createComponents()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'components.view' => false,
// 'components.create' => true,
// 'components.edit' => false,
// 'components.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_edit_components_permissions_can_edit_components()
// {
// $u = \App\Models\User::factory()->editComponents()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'components.view' => false,
// 'components.create' => false,
// 'components.edit' => true,
// 'components.delete' => false,
// ]);
// $this->hitRoutes($permissions, $u);
// }
// /**
// * @test
// */
// public function a_user_with_delete_components_permissions_can_delete_components()
// {
// $u = \App\Models\User::factory()->deleteComponents()->create();
// $permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noUsers;
// $permissions = array_merge($permissions, [
// 'components.view' => false,
// 'components.create' => false,
// 'components.edit' => false,
// 'components.delete' => true,
// ]);
// // dd($u);
// $this->hitRoutes($permissions, $u);
// }
// private function hitRoutes(array $routes, User $user)
// {
// foreach ($routes as $route => $expectation) {
// $this->assertEquals($user->hasAccess($route), $expectation);
// }
// }
}

View file

@ -1,6 +1,8 @@
<?php
namespace Tests\Unit;
use App\Models\SnipeModel;
use Tests\Unit\BaseTest;
class SnipeModelTest extends BaseTest
{

View file

@ -0,0 +1,52 @@
<?php
namespace Tests\Unit;
use App\Models\Statuslabel;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\Unit\BaseTest;
class StatuslabelTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testRTDStatuslabelAdd()
{
$statuslabel = Statuslabel::factory()->rtd()->create();
$this->assertModelExists($statuslabel);
}
public function testPendingStatuslabelAdd()
{
$statuslabel = Statuslabel::factory()->pending()->create();
$this->assertModelExists($statuslabel);
}
public function testArchivedStatuslabelAdd()
{
$statuslabel = Statuslabel::factory()->archived()->create();
$this->assertModelExists($statuslabel);
}
public function testOutForRepairStatuslabelAdd()
{
$statuslabel = Statuslabel::factory()->outForRepair()->create();
$this->assertModelExists($statuslabel);
}
public function testBrokenStatuslabelAdd()
{
$statuslabel = Statuslabel::factory()->broken()->create();
$this->assertModelExists($statuslabel);
}
public function testLostStatuslabelAdd()
{
$statuslabel = Statuslabel::factory()->lost()->create();
$this->assertModelExists($statuslabel);
}
}

View file

@ -1,10 +1,11 @@
<?php
namespace Tests\Unit;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Hash;
use Tests\Unit\BaseTest;
class UserTest extends BaseTest
{
@ -13,27 +14,12 @@ class UserTest extends BaseTest
*/
protected $tester;
// public function testUserAdd()
// {
// $user = factory(User::class)->make();
// $values = [
// 'first_name' => $user->first_name,
// 'last_name' => $user->last_name,
// 'email' => $user->email,
// 'username' => $user->username,
// 'password' => $user->password,
// ];
// User::create($values);
// $this->tester->seeRecord('users', $values);
// }
public function testFirstNameSplit()
{
$fullname = "Natalia Allanovna Romanova-O'Shostakova";
$expected_firstname = 'Natalia';
$expected_lastname = "Allanovna Romanova-O'Shostakova";
$user = User::generateFormattedNameFromFullName('firstname', $fullname);
$user = User::generateFormattedNameFromFullName($fullname, 'firstname');
$this->assertEquals($expected_firstname, $user['first_name']);
$this->assertEquals($expected_lastname, $user['last_name']);
}
@ -73,8 +59,8 @@ class UserTest extends BaseTest
public function testFirstInitialUnderscoreLastName()
{
$fullname = "Natalia Allanovna Romanova-O'Shostakova";
$expected_username = 'n_allanovna-romanova-oshostakova';
$user = User::generateFormattedNameFromFullName($fullname, 'firstname_lastname');
$expected_username = 'nallanovna-romanova-oshostakova';
$user = User::generateFormattedNameFromFullName($fullname, 'firstinitial_lastname');
$this->assertEquals($expected_username, $user['username']);
}
@ -82,7 +68,7 @@ class UserTest extends BaseTest
{
$fullname = 'Natalia';
$expected_username = 'natalia';
$user = User::generateFormattedNameFromFullName('firstname_lastname', $fullname);
$user = User::generateFormattedNameFromFullName($fullname, 'firstname_lastname',);
$this->assertEquals($expected_username, $user['username']);
}

View file

@ -1,100 +0,0 @@
<?php
use App\Models\Accessory;
use App\Models\Category;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Hash;
class AccessoryTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testFailsEmptyValidation()
{
// An Accessory requires a name, a qty, and a category_id.
$a = Accessory::create();
$this->assertFalse($a->isValid());
$fields = [
'name' => 'name',
'qty' => 'qty',
'category_id' => 'category id',
];
$errors = $a->getErrors();
foreach ($fields as $field => $fieldTitle) {
$this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required.");
}
}
public function testFailsMinValidation()
{
// An Accessory name has a min length of 3
// An Accessory has a min qty of 1
// An Accessory has a min amount of 0
$a = Accessory::factory()->make([
'name' => 'a',
'qty' => 0,
'min_amt' => -1,
]);
$fields = [
'name' => 'name',
'qty' => 'qty',
'min_amt' => 'min amt',
];
$this->assertFalse($a->isValid());
$errors = $a->getErrors();
foreach ($fields as $field => $fieldTitle) {
$this->assertStringContainsString("The ${fieldTitle} must be at least", $errors->get($field)[0]);
}
}
public function testCategoryIdMustExist()
{
$category = $this->createValidCategory('accessory-keyboard-category', ['category_type' => 'accessory']);
$accessory = Accessory::factory()->appleBtKeyboard()->make(['category_id' => $category->id]);
$this->createValidManufacturer('apple');
$accessory->save();
$this->assertTrue($accessory->isValid());
$newId = $category->id + 1;
$accessory = Accessory::factory()->appleBtKeyboard()->make(['category_id' => $newId]);
$accessory->save();
$this->assertFalse($accessory->isValid());
$this->assertStringContainsString('The selected category id is invalid.', $accessory->getErrors()->get('category_id')[0]);
}
public function testAnAccessoryBelongsToACompany()
{
$accessory = Accessory::factory()
->create(['company_id' => \App\Models\Company::factory()->create()->id]);
$this->assertInstanceOf(App\Models\Company::class, $accessory->company);
}
public function testAnAccessoryHasALocation()
{
$accessory = Accessory::factory()
->create(['location_id' => \App\Models\Location::factory()->create()->id]);
$this->assertInstanceOf(App\Models\Location::class, $accessory->location);
}
public function testAnAccessoryBelongsToACategory()
{
$accessory = Accessory::factory()->appleBtKeyboard()
->create(['category_id' => Category::factory()->accessoryKeyboardCategory()->create(['category_type' => 'accessory'])->id]);
$this->assertInstanceOf(App\Models\Category::class, $accessory->category);
$this->assertEquals('accessory', $accessory->category->category_type);
}
public function testAnAccessoryHasAManufacturer()
{
$this->createValidManufacturer('apple');
$this->createValidCategory('accessory-keyboard-category');
$accessory = Accessory::factory()->appleBtKeyboard()->create(['category_id' => 1]);
$this->assertInstanceOf(App\Models\Manufacturer::class, $accessory->manufacturer);
}
}

View file

@ -1,68 +0,0 @@
<?php
use App\Models\Asset;
use App\Models\AssetModel;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Hash;
class AssetModelTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testAnAssetModelRequiresAttributes()
{
// An Asset Model requires a name, a category_id, and a manufacturer_id.
$a = AssetModel::create();
$this->assertFalse($a->isValid());
$fields = [
'name' => 'name',
'manufacturer_id' => 'manufacturer id',
'category_id' => 'category id',
];
$errors = $a->getErrors();
foreach ($fields as $field => $fieldTitle) {
$this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required.");
}
}
public function testAnAssetModelZerosOutBlankEols()
{
$am = new AssetModel;
$am->eol = '';
$this->assertTrue($am->eol === 0);
$am->eol = '4';
$this->assertTrue($am->eol == 4);
}
public function testAnAssetModelContainsAssets()
{
$assetModel = $this->createValidAssetModel();
$this->createValidAsset([
'model_id' => $assetModel->id,
]);
$this->assertEquals(1, $assetModel->assets()->count());
}
public function testAnAssetModelHasACategory()
{
$assetmodel = $this->createValidAssetModel();
$this->assertInstanceOf(App\Models\Category::class, $assetmodel->category);
}
public function testAnAssetModelHasADepreciation()
{
$assetmodel = $this->createValidAssetModel();
$this->assertInstanceOf(App\Models\Depreciation::class, $assetmodel->depreciation);
}
public function testAnAssetModelHasAManufacturer()
{
$assetmodel = $this->createValidAssetModel();
$this->assertInstanceOf(App\Models\Manufacturer::class, $assetmodel->manufacturer);
}
}

View file

@ -1,323 +0,0 @@
<?php
use App\Exceptions\CheckoutNotAllowed;
use App\Models\Asset;
use App\Models\AssetModel;
use App\Models\Company;
use App\Models\Location;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Hash;
class AssetTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testFailsEmptyValidation()
{
// An Asset requires a name, a qty, and a category_id.
$a = Asset::create();
$this->assertFalse($a->isValid());
$fields = [
'model_id' => 'model id',
'status_id' => 'status id',
'asset_tag' => 'asset tag',
];
$errors = $a->getErrors();
foreach ($fields as $field => $fieldTitle) {
$this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required.");
}
}
public function testAutoIncrementMixed()
{
$expected = '123411';
$next = Asset::nextAutoIncrement(
collect([
['asset_tag' => '0012345'],
['asset_tag' => 'WTF00134'],
['asset_tag' => 'WTF-745'],
['asset_tag' => '0012346'],
['asset_tag' => '00123410'],
['asset_tag' => 'U8T7597h77'],
])
);
\Log::debug(print_r($next));
$this->assertEquals($expected, $next);
}
public function testAutoIncrementMixedFullTagNumber()
{
$expected = '123411';
$next = Asset::nextAutoIncrement(
[
['asset_tag' => '0012345'],
['asset_tag' => 'WTF00134'],
['asset_tag' => 'WTF-745'],
['asset_tag' => '0012346'],
['asset_tag' => '00123410'],
['asset_tag' => 'U8T7597h77'],
]
);
$this->assertEquals($expected, $next);
}
/**
* @test
*/
public function testWarrantyExpiresAttribute()
{
$asset = Asset::factory()->laptopMbp()->create([
'model_id' => $this->createValidAssetModel()->id,
'supplier_id' => $this->createvalidSupplier()->id,
'rtd_location_id' => $this->createValidLocation()->id,
]);
$asset->purchase_date = Carbon::createFromDate(2017, 1, 1)->hour(0)->minute(0)->second(0);
$asset->warranty_months = 24;
$asset->save();
$saved_asset = Asset::find($asset->id);
$this->tester->assertInstanceOf(\DateTime::class, $saved_asset->purchase_date);
$this->tester->assertEquals(
Carbon::createFromDate(2017, 1, 1)->format('Y-m-d'),
$saved_asset->purchase_date->format('Y-m-d')
);
$this->tester->assertEquals(
Carbon::createFromDate(2017, 1, 1)->setTime(0, 0, 0),
$saved_asset->purchase_date
);
$this->tester->assertEquals(24, $saved_asset->warranty_months);
$this->tester->assertInstanceOf(\DateTime::class, $saved_asset->warranty_expires);
$this->tester->assertEquals(
Carbon::createFromDate(2019, 1, 1)->format('Y-m-d'),
$saved_asset->warranty_expires->format('Y-m-d')
);
$this->tester->assertEquals(
Carbon::createFromDate(2019, 1, 1)->setTime(0, 0, 0),
$saved_asset->warranty_expires
);
}
public function testModelIdMustExist()
{
$model = $this->createValidAssetModel();
$asset = Asset::factory()->make([
'model_id' => $model->id,
'supplier_id' => $this->createValidSupplier()->id,
'rtd_location_id' => $this->createValidLocation()->id,
]);
$asset->save();
$this->assertTrue($asset->isValid());
$newId = $model->id + 1;
$asset = Asset::factory()->make(['model_id' => $newId]);
$asset->save();
$this->assertFalse($asset->isValid());
}
public function testAnAssetHasRelationships()
{
$asset = Asset::factory()->laptopMbp()
->create([
'model_id' => $this->createValidAssetModel()->id,
'company_id' => $this->createValidCompany()->id,
'supplier_id' => $this->createValidSupplier()->id,
]);
$this->assertInstanceOf(AssetModel::class, $asset->model);
$this->assertInstanceOf(Company::class, $asset->company);
$this->assertInstanceOf(App\Models\Depreciation::class, $asset->depreciation);
$this->assertInstanceOf(App\Models\Statuslabel::class, $asset->assetstatus);
$this->assertInstanceOf(App\Models\Supplier::class, $asset->supplier);
}
public function testAnAssetCanBeAvailableForCheckout()
{
// Logic: If the asset is not assigned to anyone,
// and the statuslabel type is "deployable"
// and the asset is not deleted
// Then it is available for checkout
// An asset assigned to someone should not be available for checkout.
$assetAssigned = Asset::factory()->laptopMbp()->assignedToUser()
->create(['model_id' => $this->createValidAssetModel()]);
$this->assertFalse($assetAssigned->availableForCheckout());
// An asset with a non deployable statuslabel should not be available for checkout.
$assetUndeployable = Asset::factory()->create([
'status_id' => $this->createValidStatuslabel('archived')->id,
'model_id' => $this->createValidAssetModel(),
]);
$this->assertFalse($assetUndeployable->availableForCheckout());
// An asset that has been deleted is not avaiable for checkout.
$assetDeleted = Asset::factory()->deleted()->create([
'model_id' => $this->createValidAssetModel(),
]);
$this->assertFalse($assetDeleted->availableForCheckout());
// A ready to deploy asset that isn't assigned to anyone is available for checkout
$asset = Asset::factory()->create([
'status_id' => $this->createValidStatuslabel('rtd')->id,
'model_id' => $this->createValidAssetModel(),
]);
$this->assertTrue($asset->availableForCheckout());
}
public function testAnAssetCanHaveComponents()
{
$asset = $this->createValidAsset();
$components = \App\Models\Component::factory()->count(5)->ramCrucial4()->create([
'category_id' => $this->createValidCategory('component-hdd-category')->id,
]);
$components->each(function ($component) use ($asset) {
$component->assets()->attach($component, [
'asset_id'=>$asset->id,
]);
});
$this->assertInstanceOf(App\Models\Component::class, $asset->components()->first());
$this->assertCount(5, $asset->components);
}
public function testAnAssetCanHaveUploads()
{
$asset = $this->createValidAsset([
'supplier_id' => $this->createValidSupplier()->id,
]);
$this->assertCount(0, $asset->uploads);
\App\Models\Actionlog::factory()->count('asset-upload')->create(['item_id' => $asset->id]);
$this->assertCount(1, $asset->fresh()->uploads);
}
// Helper Method for checking in assets.... We should extract this to the model or a trait.
private function checkin($asset, $target)
{
$asset->expected_checkin = null;
$asset->last_checkout = null;
$asset->assigned_to = null;
$asset->assigned_type = null;
$asset->location_id = $asset->rtd_location_id;
$asset->assignedTo()->disassociate($asset);
$asset->accepted = null;
$asset->save();
$asset->logCheckin($target, 'Test Checkin');
}
public function testAnAssetCanBeCheckedOut()
{
// This tests Asset::checkOut(), Asset::assignedTo(), Asset::assignedAssets(), Asset::assetLoc(), Asset::assignedType(), defaultLoc()
$asset = $this->createValidAsset();
$adminUser = $this->signIn();
$target = \App\Models\User::factory()->create([
'location_id' => \App\Models\Location::factory()->create(),
]);
// An Asset Can be checked out to a user, and this should be logged.
$asset->checkOut($target, $adminUser);
$asset->save();
$this->assertInstanceOf(App\Models\User::class, $asset->assignedTo);
$this->assertEquals($asset->location->id, $target->userLoc->id);
$this->assertEquals('user', $asset->assignedType());
$this->assertEquals($asset->defaultLoc->id, $asset->rtd_location_id);
$this->tester->seeRecord('action_logs', [
'action_type' => 'checkout',
'target_type' => get_class($target),
'target_id' => $target->id,
]);
$this->tester->seeRecord('assets', [
'id' => $asset->id,
'assigned_to' => $target->id,
'assigned_type' => User::class,
]);
$this->checkin($asset, $target);
$this->assertNull($asset->fresh()->assignedTo);
$this->tester->seeRecord('action_logs', [
'action_type' => 'checkin from',
'target_type' => get_class($target),
'target_id' => $target->id,
]);
$this->tester->seeRecord('assets', [
'id' => $asset->id,
'assigned_to' => null,
'assigned_type' => null,
]);
// An Asset Can be checked out to a asset, and this should be logged.
$target = $this->createValidAsset();
$asset->checkOut($target, $adminUser);
$asset->save();
$this->assertInstanceOf(App\Models\Asset::class, $asset->fresh()->assignedTo);
$this->assertEquals($asset->fresh()->location->id, $target->fresh()->location->id);
$this->assertEquals('asset', $asset->assignedType());
$this->assertEquals($asset->defaultLoc->id, $asset->rtd_location_id);
$this->tester->seeRecord('action_logs', [
'action_type' => 'checkout',
'target_type' => get_class($target),
'target_id' => $target->id,
]);
$this->assertCount(1, $target->assignedAssets);
$this->checkin($asset, $target);
$this->assertNull($asset->fresh()->assignedTo);
$this->tester->seeRecord('action_logs', [
'action_type' => 'checkin from',
'target_type' => get_class($target),
'target_id' => $target->id,
]);
// An Asset cannot be checked out to itself.
$target = $this->createValidAsset();
$this->expectException(CheckoutNotAllowed::class);
$target->checkOut($target, $adminUser);
// An Asset Can be checked out to a location, and this should be logged.
$target = $this->createValidLocation();
$asset->checkOut($target, $adminUser);
$asset->save();
$this->assertInstanceOf(App\Models\Location::class, $asset->fresh()->assignedTo);
$this->assertEquals($asset->fresh()->location->id, $target->fresh()->id);
$this->assertEquals('location', $asset->assignedType());
$this->assertEquals($asset->defaultLoc->id, $asset->rtd_location_id);
$this->tester->seeRecord('action_logs', [
'action_type' => 'checkout',
'target_type' => get_class($target),
'target_id' => $target->id,
]);
$this->checkin($asset, $target);
$this->assertNull($asset->fresh()->assignedTo);
$this->tester->seeRecord('action_logs', [
'action_type' => 'checkin from',
'target_type' => get_class($target),
'target_id' => $target->id,
]);
}
public function testAnAssetHasMaintenances()
{
$asset = $this->createValidAsset();
\App\Models\AssetMaintenance::factory()->create(['asset_id' => $asset->id]);
$this->assertCount(1, $asset->assetmaintenances);
}
}

View file

@ -1,73 +0,0 @@
<?php
use App\Models\Category;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Hash;
class CategoryTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testFailsEmptyValidation()
{
// An Asset requires a name, a qty, and a category_id.
$a = Category::create();
$this->assertFalse($a->isValid());
$fields = [
'name' => 'name',
'category_type' => 'category type',
];
$errors = $a->getErrors();
foreach ($fields as $field => $fieldTitle) {
$this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required.");
}
}
public function testACategoryCanHaveAssets()
{
$this->createValidAssetModel(); //This will seed various things to make the following work better.
$category = $this->createValidCategory('asset-desktop-category');
$models = \App\Models\AssetModel::factory()->count(5)->mbp13Model()->create(['category_id' => $category->id]);
$this->assertEquals(5, $category->models->count());
$this->assertCount(5, $category->models);
$models->each(function ($model) {
// This is intentionally run twice to generate the ten imagined assets, done this way to keep it in sync with createValidAsset rather than using the factory directly.
$this->createValidAsset(['model_id' => $model->id]);
$this->createValidAsset(['model_id' => $model->id]);
});
$this->assertEquals(10, $category->itemCount());
}
public function testACategoryCanHaveAccessories()
{
$category = $this->createValidCategory('accessory-keyboard-category');
\App\Models\Accessory::factory()->count(5)->appleBtKeyboard()->create(['category_id' => $category->id]);
$this->assertCount(5, $category->accessories);
$this->assertEquals(5, $category->itemCount());
}
public function testACategoryCanHaveConsumables()
{
$category = $this->createValidCategory('consumable-paper-category');
\App\Models\Consumable::factory()->count(5)->cardstock()->create(['category_id' => $category->id]);
$this->assertCount(5, $category->consumables);
$this->assertEquals(5, $category->itemCount());
}
public function testACategoryCanHaveComponents()
{
$category = $this->createValidCategory('component-ram-category');
\App\Models\Component::factory()->count(5)->ramCrucial4()->create(['category_id' => $category->id]);
$this->assertCount(5, $category->components);
$this->assertEquals(5, $category->itemCount());
}
}

View file

@ -1,86 +0,0 @@
<?php
use App\Models\Company;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Hash;
class CompanyTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testFailsEmptyValidation()
{
// An Company requires a name, a qty, and a category_id.
$a = Company::create();
$this->assertFalse($a->isValid());
$fields = [
'name' => 'name',
];
$errors = $a->getErrors();
foreach ($fields as $field => $fieldTitle) {
$this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required.");
}
}
public function testACompanyCanHaveUsers()
{
$company = $this->createValidCompany();
$user = $this->createValidUser(['company_id'=>$company->id]);
$this->assertCount(1, $company->users);
}
public function testACompanyCanHaveAssets()
{
$company = $this->createValidCompany();
$this->createValidAsset(['company_id' => $company->id]);
$this->assertCount(1, $company->assets);
}
public function testACompanyCanHaveLicenses()
{
$company = $this->createValidCompany();
\App\Models\License::factory()->count(1)->acrobat()->create([
'company_id'=>$company->id,
'manufacturer_id' => \App\Models\Manufacturer::factory()->adobe()->create()->id,
'category_id' => \App\Models\Category::factory()->licenseOfficeCategory()->create()->id,
]);
$this->assertCount(1, $company->licenses);
}
public function testACompanyCanHaveAccessories()
{
$company = $this->createValidCompany();
$a = \App\Models\Accessory::factory()->appleBtKeyboard()->create([
'category_id' => \App\Models\Category::factory()->accessoryKeyboardCategory()->create()->id,
'company_id' => $company->id,
]);
$this->assertCount(1, $company->accessories);
}
public function testACompanyCanHaveConsumables()
{
$company = $this->createValidCompany();
\App\Models\Consumable::factory()->count(1)->cardstock()->create([
'company_id' => $company->id,
'category_id' => \App\Models\Category::factory()->consumablePaperCategory()->create()->id,
]);
$this->assertCount(1, $company->consumables);
}
public function testACompanyCanHaveComponents()
{
$company = $this->createValidCompany();
\App\Models\Component::factory()->count(1)->ramCrucial4()->create([
'company_id'=>$company->id,
'category_id' => \App\Models\Category::factory()->componentRamCategory()->create()->id,
]);
$this->assertCount(1, $company->components);
}
}

View file

@ -1,99 +0,0 @@
<?php
use App\Models\Category;
use App\Models\Company;
use App\Models\Component;
use App\Models\Location;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Hash;
class ComponentTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testFailsEmptyValidation()
{
// An Component requires a name, a qty, and a category_id.
$a = Component::create();
$this->assertFalse($a->isValid());
$fields = [
'name' => 'name',
'qty' => 'qty',
'category_id' => 'category id',
];
$errors = $a->getErrors();
foreach ($fields as $field => $fieldTitle) {
$this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required.");
}
}
public function testFailsMinValidation()
{
// An Component name has a min length of 3
// An Component has a min qty of 1
// An Component has a min amount of 0
$a = Component::factory()->make([
'name' => 'a',
'qty' => 0,
'min_amt' => -1,
]);
$fields = [
'name' => 'name',
'qty' => 'qty',
'min_amt' => 'min amt',
];
$this->assertFalse($a->isValid());
$errors = $a->getErrors();
foreach ($fields as $field => $fieldTitle) {
$this->assertStringContainsString("The ${fieldTitle} must be at least", $errors->get($field)[0]);
}
}
public function testCategoryIdMustExist()
{
$category = $this->createValidCategory('component-hdd-category',
['category_type' => 'component']);
$component = Component::factory()->ssdCrucial240()
->make(['category_id' => $category->id]);
$this->createValidManufacturer('apple');
$component->save();
$this->assertTrue($component->isValid());
$newId = $category->id + 1;
$component = Component::factory()->ssdCrucial240()->make(['category_id' => $newId]);
$component->save();
$this->assertFalse($component->isValid());
$this->assertStringContainsString('The selected category id is invalid.', $component->getErrors()->get('category_id')[0]);
}
public function testAnComponentBelongsToACompany()
{
$component = Component::factory()
->create(['company_id' => Company::factory()->create()->id]);
$this->assertInstanceOf(Company::class, $component->company);
}
public function testAnComponentHasALocation()
{
$component = Component::factory()
->create(['location_id' => Location::factory()->create()->id]);
$this->assertInstanceOf(Location::class, $component->location);
}
public function testAnComponentBelongsToACategory()
{
$component = Component::factory()->ssdCrucial240()
->create([
'category_id' => Category::factory()->componentHddCategory()
->create(['category_type' => 'component'])->id,
]);
$this->assertInstanceOf(Category::class, $component->category);
$this->assertEquals('component', $component->category->category_type);
}
}

View file

@ -1,49 +0,0 @@
<?php
use App\Models\Consumable;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Hash;
class ConsumableTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testFailsEmptyValidation()
{
// An Consumable requires a name, a qty, and a category_id.
$a = Consumable::create();
$this->assertFalse($a->isValid());
$fields = [
'name' => 'name',
'qty' => 'qty',
'category_id' => 'category id',
];
$errors = $a->getErrors();
foreach ($fields as $field => $fieldTitle) {
$this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required.");
}
}
public function testAConsumableHasRelationships()
{
$consumable = Consumable::factory()->cardstock()->create([
'category_id' => $this->createValidCategory('consumable-paper-category')->id,
'manufacturer_id' => $this->createValidManufacturer('apple')->id,
'company_id' => $this->createValidCompany()->id,
'location_id' => $this->createValidLocation()->id,
'user_id' => $this->signIn()->id,
]);
$this->assertInstanceOf(App\Models\User::class, $consumable->admin);
$this->assertInstanceOf(App\Models\Company::class, $consumable->company);
$this->assertInstanceOf(App\Models\Manufacturer::class, $consumable->manufacturer);
$this->assertInstanceOf(App\Models\Location::class, $consumable->location);
$this->assertInstanceOf(App\Models\Category::class, $consumable->category);
}
}

View file

@ -1,29 +0,0 @@
<?php
use App\Models\Department;
use App\Models\Location;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Hash;
class DepartmentTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
// public function testDepartmentAdd()
// {
// $department = factory(Department::class)->make();
// $values = [
// 'name' => $department->name,
// 'user_id' => $department->user_id,
// 'manager_id' => $department->manager_id,
// ];
// Department::create($values);
// $this->tester->seeRecord('departments', $values);
// }
}

View file

@ -1,50 +0,0 @@
<?php
use App\Models\Depreciation;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
class DepreciationTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testFailsEmptyValidation()
{
// An Asset requires a name, a qty, and a category_id.
$a = Depreciation::create();
$this->assertFalse($a->isValid());
$fields = [
'name' => 'name',
'months' => 'months',
];
$errors = $a->getErrors();
foreach ($fields as $field => $fieldTitle) {
$this->assertEquals($errors->get($field)[0], "The ${fieldTitle} field is required.");
}
}
public function testADepreciationHasModels()
{
$this->createValidAssetModel();
$depreciation = $this->createValidDepreciation('computer', ['name' => 'New Depreciation']);
$models = \App\Models\AssetModel::factory()->count(5)->mbp13Model()->create(['depreciation_id'=>$depreciation->id]);
$this->assertEquals(5, $depreciation->models->count());
}
public function testADepreciationHasLicenses()
{
$category = $this->createValidCategory('license-graphics-category');
$depreciation = $this->createValidDepreciation('computer', ['name' => 'New Depreciation']);
$licenses = \App\Models\License::factory()->count(5)->photoshop()->create([
'depreciation_id'=>$depreciation->id,
'category_id' => $category->id,
]);
$this->assertEquals(5, $depreciation->licenses()->count());
}
}

View file

@ -1,746 +0,0 @@
<?php
use App\Importer\AccessoryImporter;
use App\Importer\AssetImporter;
use App\Importer\ConsumableImporter;
use App\Importer\LicenseImporter;
use App\Importer\UserImporter;
use App\Models\Accessory;
use App\Models\Asset;
use App\Models\AssetModel;
use App\Models\Category;
use App\Models\CustomField;
use App\Models\Location;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;
class ImporterTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testDefaultImportAssetWithCustomFields()
{
$this->signIn();
$csv = <<<'EOT'
Full Name,Email,Username,item Name,Category,Model name,Manufacturer,Model Number,Serial,Asset Tag,Location,Notes,Purchase Date,Purchase Cost,Company,Status,Warranty,Supplier,Weight
Bonnie Nelson,bnelson0@cdbaby.com,bnelson0,eget nunc donec quis,quam,massa id,Linkbridge,6377018600094472,27aa8378-b0f4-4289-84a4-405da95c6147,970882174-8,Daping,"Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.",2016-04-05,133289.59,Alpha,Undeployable,14,Blogspan,35
EOT;
$this->initializeCustomFields();
$this->import(new AssetImporter($csv));
$this->tester->seeRecord('users', [
'first_name' => 'Bonnie',
'last_name' => 'Nelson',
'email' => 'bnelson0@cdbaby.com',
]);
$this->tester->seeRecord('categories', [
'name' => 'quam',
]);
$this->tester->seeRecord('models', [
'name' => 'massa id',
'model_number' => 6377018600094472,
]);
$this->tester->seeRecord('manufacturers', [
'name' => 'Linkbridge',
]);
$this->tester->seeRecord('locations', [
'name' => 'Daping',
]);
$this->tester->seeRecord('companies', [
'name' => 'Alpha',
]);
$this->tester->seeRecord('status_labels', [
'name' => 'Undeployable',
]);
$this->tester->seeRecord('suppliers', [
'name' => 'Blogspan',
]);
$this->tester->seeRecord('assets', [
'name' => 'eget nunc donec quis',
'serial' => '27aa8378-b0f4-4289-84a4-405da95c6147',
'asset_tag' => '970882174-8',
'notes' => 'Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.',
'purchase_date' => '2016-04-05 00:00:01',
'purchase_cost' => 133289.59, 'warranty_months' => 14,
'_snipeit_weight_2' => 35,
]);
}
public function testImportCheckoutToLocation()
{
$this->signIn();
// Testing in order:
// * Asset to user, no checkout type defined (default to user).
// * Asset to user, explicit user checkout type (Checkout to user)
// * Asset to location, location does not exist to begin with
// * Asset to preexisting location.
$csv = <<<'EOT'
Full Name,Email,Username,Checkout Location,Checkout Type,item Name,Category,Model name,Manufacturer,Model Number,Serial,Asset Tag,Location,Notes,Purchase Date,Purchase Cost,Company,Status,Warranty,Supplier,Weight
Bonnie Nelson,bnelson0@cdbaby.com,bnelson0,,,eget nunc donec quis,quam,massa id,Linkbridge,6377018600094472,27aa8378-b0f4-4289-84a4-405da95c6147,970882174-8,Daping,"Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.",2016-04-05,133289.59,Alpha,Undeployable,14,Blogspan,35
Mildred Gibson,mgibson2@wiley.com,mgibson2,,user,morbi quis tortor id,nunc nisl duis,convallis tortor risus,Lajo,374622546776765,2837ab20-8f0d-4935-8a52-226392f2b1b0,710141467-2,Shekou,In congue. Etiam justo. Etiam pretium iaculis justo.,2015-08-09,233.57,Konklab,Lost,,,
,,,Planet Earth,location,dictumst maecenas ut,sem praesent,accumsan felis,Layo,30052522651756,4751495c-cee0-4961-b788-94a545b5643e,998233705-X,Dante Delgado,,2016-04-16,261.79,,Archived,15,Ntag,
,,,Daping,location,viverra diam vitae,semper sapien,dapibus dolor vel,Flashset,3559785746335392,e287bb64-ff4f-434c-88ab-210ad433c77b,927820758-6,Achiaman,,2016-03-05,675.3,,Archived,22,Meevee,
EOT;
$this->import(new AssetImporter($csv));
$user = User::where('username', 'bnelson0')->firstOrFail();
$this->tester->seeRecord('assets', [
'asset_tag' => '970882174-8',
'assigned_type' => User::class,
'assigned_to' => $user->id,
]);
$user = User::where('username', 'mgibson2')->firstOrFail();
$this->tester->seeRecord('assets', [
'asset_tag' => '710141467-2',
'assigned_type' => User::class,
'assigned_to' => $user->id,
]);
$location = Location::where('name', 'Planet Earth')->firstOrFail();
$this->tester->seeRecord('assets', [
'asset_tag' => '998233705-X',
'assigned_type' => Location::class,
'assigned_to' => $location->id,
]);
$location = Location::where('name', 'Daping')->firstOrFail();
$this->tester->seeRecord('assets', [
'asset_tag' => '927820758-6',
'assigned_type' => Location::class,
'assigned_to' => $location->id,
]);
}
public function testUpdateAssetIncludingCustomFields()
{
$this->signIn();
$csv = <<<'EOT'
Name,Email,Username,item Name,Category,Model name,Manufacturer,Model Number,Serial,Asset Tag,Location,Notes,Purchase Date,Purchase Cost,Company,Status,Warranty,Supplier,weight
Bonnie Nelson,bnelson0@cdbaby.com,bnelson0,eget nunc donec quis,quam,massa id,Linkbridge,6377018600094472,27aa8378-b0f4-4289-84a4-405da95c6147,970882174-8,Daping,"Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.",2016-04-05,133289.59,Alpha,Undeployable,14,Blogspan,95
EOT;
$this->initializeCustomFields();
$this->import(new AssetImporter($csv));
$updatedCSV = <<<'EOT'
item Name,Category,Model name,Manufacturer,Model Number,Serial,Asset Tag,Location,Notes,Purchase Date,Purchase Cost,Company,Status,Warranty,Supplier
A new name,some other category,Another Model,Linkbridge 32,356,67433477,970882174-8,New Location,I have no notes,2018-04-05,25.59,Another Company,Ready To Go,18,Not Creative
EOT;
$importer = new AssetImporter($updatedCSV);
$importer->setUserId(1)
->setUpdating(true)
->setUsernameFormat('firstname.lastname')
->import();
$this->tester->seeRecord('categories', [
'name' => 'some other category',
]);
$this->tester->seeRecord('models', [
'name' => 'Another Model',
'model_number' => 356,
]);
$this->tester->seeRecord('manufacturers', [
'name' => 'Linkbridge 32',
]);
$this->tester->seeRecord('locations', [
'name' => 'New Location',
]);
$this->tester->seeRecord('companies', [
'name' => 'Another Company',
]);
$this->tester->seeRecord('status_labels', [
'name' => 'Ready To Go',
]);
$this->tester->seeRecord('suppliers', [
'name' => 'Not Creative',
]);
$this->tester->seeRecord('assets', [
'name' => 'A new name',
'serial' => '67433477',
'asset_tag' => '970882174-8',
'notes' => 'I have no notes',
'purchase_date' => '2018-04-05 00:00:01',
'purchase_cost' => 25.59,
'warranty_months' => 18,
'_snipeit_weight_2' => 95,
]);
}
public function testAssetModelNumber4359()
{
// As per bug #4359
// 1) Create model with blank model # and custom field.
// 2 ) Update custom fields with a csv not including model #
// 3 ) Not updated. NULL vs. empty issue.
$this->signIn();
$csv = <<<'EOT'
Name,Email,Username,item Name,Category,Model name,Manufacturer,Serial,Asset Tag,Location,Notes,Purchase Date,Purchase Cost,Company,Status,Warranty,Supplier
Bonnie Nelson,bnelson0@cdbaby.com,bnelson0,eget nunc donec quis,quam,massa id,Linkbridge,27aa8378-b0f4-4289-84a4-405da95c6147,970882174-8,Daping,"Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.",2016-04-05,133289.59,Alpha,Undeployable,14,Blogspan
EOT;
// Need to do this manually...
$customField = \App\Models\CustomField::factory()->create(['name' => 'Weight']);
$customFieldSet = \App\Models\CustomFieldset::factory()->create(['name' => 'Default']);
$customFieldSet->fields()->attach($customField, [
'required' => false,
'order' => 'asc', ]);
\App\Models\Category::factory()->assetLaptopCategory()->create([
'name' => 'quam',
]);
\App\Models\Manufacturer::factory()->apple()->create([
'name' => 'Linkbridge',
]);
$am = \App\Models\AssetModel::factory()->create([
'name' => 'massa id',
'fieldset_id' => $customFieldSet->id,
'category_id' => 1,
'manufacturer_id' => 1,
'model_number' => null,
]);
$this->import(new AssetImporter($csv));
$updatedCSV = <<<'EOT'
Serial,Asset Tag,weight
67433477,970882174-8,115
EOT;
$importer = new AssetImporter($updatedCSV);
$importer->setUserId(1)
->setUpdating(true)
->setUsernameFormat('firstname.lastname')
->import();
$this->tester->seeRecord('assets', [
'asset_tag' => '970882174-8',
'_snipeit_weight_2' => 115,
]);
}
public function initializeCustomFields()
{
$customField = \App\Models\CustomField::factory()->create(['name' => 'Weight']);
$customFieldSet = \App\Models\CustomFieldset::factory()->create(['name' => 'Default']);
$customFieldSet->fields()->attach($customField, [
'required' => false,
'order' => 'asc', ]);
$am = \App\Models\AssetModel::factory()->create([
'name' => 'massa id',
'fieldset_id' => $customFieldSet->id,
]);
}
public function testCustomMappingImport()
{
$this->signIn();
$csv = <<<'EOT'
Full Name,Email,Username,object name,Cat,Model name,Manufacturer,Model Number,Serial,Asset,Loc,Some Notes,Purchase Date,Purchase Cost,comp,Status,Warranty,Supplier
Bonnie Nelson,bnelson0@cdbaby.com,bnelson0,eget nunc donec quis,quam,massa id,Linkbridge,6377018600094472,27aa8378-b0f4-4289-84a4-405da95c6147,970882174-8,Daping,"Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.",2016-04-05,133289.59,Alpha,Undeployable,14,Blogspan
EOT;
$customFieldMap = [
'asset_tag' => 'Asset',
'category' => 'Cat',
'company' => 'comp',
'item_name' => 'object name',
'expiration_date' => 'expiration date',
'location' => 'loc',
'notes' => 'Some Notes',
'asset_model' => 'model name',
];
$this->import(new AssetImporter($csv), $customFieldMap);
// Did we create a user?
$this->tester->seeRecord('users', [
'first_name' => 'Bonnie',
'last_name' => 'Nelson',
'email' => 'bnelson0@cdbaby.com',
]);
// Grab the user record for use in asserting assigned_to
$createdUser = $this->tester->grabRecord('users', [
'first_name' => 'Bonnie',
'last_name' => 'Nelson',
'email' => 'bnelson0@cdbaby.com',
]);
$this->tester->seeRecord('categories', [
'name' => 'quam',
]);
$this->tester->seeRecord('models', [
'name' => 'massa id',
'model_number' => 6377018600094472,
]);
$this->tester->seeRecord('manufacturers', [
'name' => 'Linkbridge',
]);
$this->tester->seeRecord('locations', [
'name' => 'Daping',
]);
$this->tester->seeRecord('companies', [
'name' => 'Alpha',
]);
$this->tester->seeRecord('status_labels', [
'name' => 'Undeployable',
]);
$this->tester->seeRecord('suppliers', [
'name' => 'Blogspan',
]);
$this->tester->seeRecord('assets', [
'name' => 'eget nunc donec quis',
'serial' => '27aa8378-b0f4-4289-84a4-405da95c6147',
'asset_tag' => '970882174-8',
'notes' => 'Curabitur in libero ut massa volutpat convallis. Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.',
'purchase_date' => '2016-04-05 00:00:01',
'purchase_cost' => 133289.59,
'warranty_months' => 14,
'assigned_to' => $createdUser['id'],
'assigned_type' => User::class,
]);
}
public function testDefaultAccessoryImport()
{
$csv = <<<'EOT'
Item Name,Purchase Date,Purchase Cost,Location,Company,Order Number,Category,Requestable,Quantity
Walter Carter,09/01/2006,,metus. Vivamus,Macromedia,J935H60W,Customers,False,278
EOT;
$this->import(new AccessoryImporter($csv));
$this->tester->seeRecord('accessories', [
'name' => 'Walter Carter',
'purchase_date' => '2006-09-01 00:00:01',
'order_number' => 'J935H60W',
'requestable' => 0,
'qty' => 278,
]);
$this->tester->seeRecord('locations', [
'name' => 'metus. Vivamus',
]);
$this->tester->seeRecord('companies', [
'name' => 'Macromedia',
]);
$this->tester->seeRecord('categories', [
'name' => 'Customers',
]);
}
public function testDefaultAccessoryUpdate()
{
$csv = <<<'EOT'
Item Name,Purchase Date,Purchase Cost,Location,Company,Order Number,Category,Requestable,Quantity
Walter Carter,09/01/2006,,metus. Vivamus,Macromedia,J935H60W,Customers,False,278
EOT;
$this->import(new AccessoryImporter($csv));
$this->tester->seeNumRecords(1, 'accessories');
$updatedCSV = <<<'EOT'
Item Name,Purchase Date,Purchase Cost,Location,Company,Order Number,Category,Requestable,Quantity
Walter Carter,09/01/2015,350,metus. Vivamus,Macromedia,35GGH,Customers,True,12
EOT;
$importer = new AccessoryImporter($updatedCSV);
$importer->setUserId(1)
->setUpdating(true)
->import();
// At this point we should still only have one record.
$this->tester->seeNumRecords(1, 'accessories');
// But instead these.
$this->tester->seeRecord('accessories', [
'name' => 'Walter Carter',
'purchase_date' => '2015-09-01 00:00:01',
'order_number' => '35GGH',
'requestable' => 1,
'qty' => 12,
]);
}
public function testCustomAccessoryImport()
{
$csv = <<<'EOT'
Name,Pur Date,Cost,Loc,Comp,Order Num,Cat,Request,Quan
Walter Carter,09/01/2006,,metus. Vivamus,Macromedia,J935H60W,Customers,False,278
EOT;
$customFieldMap = [
'category' => 'Cat',
'company' => 'Comp',
'item_name' => 'Name',
'location' => 'Loc',
'purchase_date' => 'Pur Date',
'purchase_cost' => 'Cost',
'order_number' => 'Order Num',
'requestable' => 'Request',
'quantity' => 'Quan',
];
$this->import(new AccessoryImporter($csv), $customFieldMap);
// dd($this->tester->grabRecord('accessories'));
$this->tester->seeRecord('accessories', [
'name' => 'Walter Carter',
'purchase_date' => '2006-09-01 00:00:01',
'order_number' => 'J935H60W',
'requestable' => 0,
'qty' => 278,
]);
$this->tester->seeRecord('locations', [
'name' => 'metus. Vivamus',
]);
$this->tester->seeRecord('companies', [
'name' => 'Macromedia',
]);
$this->tester->seeRecord('categories', [
'name' => 'Customers',
]);
}
public function testDefaultConsumableImport()
{
$csv = <<<'EOT'
Item Name,Purchase Date,Purchase Cost,Location,Company,Order Number,Category,Requestable,Quantity,Item Number,Model Number
eget,01/03/2011,$85.91,mauris blandit mattis.,Lycos,T295T06V,Triamterene/Hydrochlorothiazide,No,322,3305,30123
EOT;
$this->import(new ConsumableImporter($csv));
$this->tester->seeRecord('consumables', [
'name' => 'eget',
'purchase_date' => '2011-01-03 00:00:01',
'purchase_cost' => 85.91,
'order_number' => 'T295T06V',
'requestable' => 0,
'qty' => 322,
'item_no' => 3305,
'model_number' => 30123,
]);
$this->tester->seeRecord('locations', [
'name' => 'mauris blandit mattis.',
]);
$this->tester->seeRecord('companies', [
'name' => 'Lycos',
]);
$this->tester->seeRecord('categories', [
'name' => 'Triamterene/Hydrochlorothiazide',
]);
}
public function testDefaultConsumableUpdate()
{
$csv = <<<'EOT'
Item Name,Purchase Date,Purchase Cost,Location,Company,Order Number,Category,Requestable,Quantity
eget,01/03/2011,85.91,mauris blandit mattis.,Lycos,T295T06V,Triamterene/Hydrochlorothiazide,No,322
EOT;
$this->import(new ConsumableImporter($csv));
$this->tester->seeNumRecords(1, 'consumables');
$updatedCSV = <<<'EOT'
Item Name,Purchase Date,Purchase Cost,Location,Company,Order Number,Category,Requestable,Quantity
eget,12/05/2016,35.45,mauris blandit mattis.,Lycos,3666FF,New Cat,Yes,15
EOT;
$importer = new ConsumableImporter($updatedCSV);
$importer->setUserId(1)
->setUpdating(true)
->import();
// At this point we should still only have one record.
$this->tester->seeNumRecords(1, 'consumables');
// But instead these.
$this->tester->seeRecord('consumables', [
'name' => 'eget',
'purchase_date' => '2016-12-05 00:00:01',
'purchase_cost' => 35.45,
'order_number' => '3666FF',
'requestable' => 1,
'qty' => 15,
]);
}
public function testCustomConsumableImport()
{
$csv = <<<'EOT'
Name,pur Date,Pur Cost,Loc,Comp,Order Num,Kat,Request,Quan
eget,01/03/2011,85.91,mauris blandit mattis.,Lycos,T295T06V,Triamterene/Hydrochlorothiazide,No,322
EOT;
$customFieldMap = [
'category' => 'Kat',
'company' => 'Comp',
'item_name' => 'Name',
'location' => 'Loc',
'purchase_date' => 'Pur date',
'purchase_cost' => 'Pur Cost',
'order_number' => 'Order Num',
'requestable' => 'Request',
'quantity' => 'Quan',
];
$this->import(new ConsumableImporter($csv), $customFieldMap);
$this->tester->seeRecord('consumables', [
'name' => 'eget',
'purchase_date' => '2011-01-03 00:00:01',
'purchase_cost' => 85.91,
'order_number' => 'T295T06V',
'requestable' => 0,
'qty' => 322,
]);
$this->tester->seeRecord('locations', [
'name' => 'mauris blandit mattis.',
]);
$this->tester->seeRecord('companies', [
'name' => 'Lycos',
]);
$this->tester->seeRecord('categories', [
'name' => 'Triamterene/Hydrochlorothiazide',
]);
}
public function testDefaultLicenseImport()
{
$this->signIn();
$csv = <<<'EOT'
Full Name,Email,Username,Item name,serial,manufacturer,purchase date,purchase cost,purchase order,order number,Licensed To Name,Licensed to Email,expiration date,maintained,reassignable,seats,company,supplier,category,notes,asset tag
Helen Anderson,cspencer0@privacy.gov.au,cspencer0,Argentum Malachite Athletes Foot Relief,1aa5b0eb-79c5-40b2-8943-5472a6893c3c,"Beer, Leannon and Lubowitz",07/13/2012,$79.66,53008,386436062-5,Cynthia Spencer,cspencer0@gov.uk,01/27/2016,false,no,80,"Haag, Schmidt and Farrell","Hegmann, Mohr and Cremin",Graphics Software,Sed ante. Vivamus tortor. Duis mattis egestas metus.,test 1
EOT;
// Force create an asset to match the checkout
$testAsset = $this->createValidAsset(['asset_tag' => 'test 1']);
$this->import(new LicenseImporter($csv));
// dd($this->tester->grabRecord('licenses'));
// Did we create a user?
$this->tester->seeRecord('users', [
'first_name' => 'Helen',
'last_name' => 'Anderson',
'email' => 'cspencer0@privacy.gov.au',
]);
// Grab the user record for use in asserting assigned_to
$createdUser = $this->tester->grabRecord('users', [
'first_name' => 'Helen',
'last_name' => 'Anderson',
'email' => 'cspencer0@privacy.gov.au',
]);
$this->tester->seeRecord('licenses', [
'name' => 'Argentum Malachite Athletes Foot Relief',
'purchase_date' => '2012-07-13 00:00:01',
'seats' => 80,
'license_email' => 'cspencer0@gov.uk',
'order_number' => '386436062-5',
'license_name' => 'Cynthia Spencer',
'expiration_date' => '2016-01-27',
'maintained' => 0,
'notes' => 'Sed ante. Vivamus tortor. Duis mattis egestas metus.',
'purchase_cost' => 79.66,
'purchase_order' => '53008',
'reassignable' => 0,
'serial' => '1aa5b0eb-79c5-40b2-8943-5472a6893c3c',
]);
$this->tester->seeRecord('manufacturers', [
'name' => 'Beer, Leannon and Lubowitz',
]);
$this->tester->seeRecord('suppliers', [
'name' => 'Hegmann, Mohr and Cremin',
]);
$this->tester->seeRecord('companies', [
'name' => 'Haag, Schmidt and Farrell',
]);
$this->tester->seeRecord('categories', [
'name' => 'Graphics Software',
]);
$this->tester->seeNumRecords(80, 'license_seats');
$this->tester->seeRecord('license_seats', [
'assigned_to' => $createdUser['id'],
'license_id' => \App\Models\License::where('serial', '1aa5b0eb-79c5-40b2-8943-5472a6893c3c')->first()->id,
'asset_id' => $testAsset->id,
]);
}
public function testDefaultLicenseUpdate()
{
$csv = <<<'EOT'
Name,Email,Username,Item name,serial,manufacturer,purchase date,purchase cost,purchase order,order number,Licensed To Name,Licensed to Email,expiration date,maintained,reassignable,seats,company,supplier,category,notes
Helen Anderson,cspencer0@privacy.gov.au,cspencer0,Argentum Malachite Athletes Foot Relief,1aa5b0eb-79c5-40b2-8943-5472a6893c3c,"Beer, Leannon and Lubowitz",07/13/2012,$79.66,53008,386436062-5,Cynthia Spencer,cspencer0@gov.uk,01/27/2016,false,no,80,"Haag, Schmidt and Farrell","Hegmann, Mohr and Cremin",Graphics Software,Sed ante. Vivamus tortor. Duis mattis egestas metus.
EOT;
$this->import(new LicenseImporter($csv));
$this->tester->seeNumRecords(1, 'licenses');
$updatedCSV = <<<'EOT'
Item name,serial,manufacturer,purchase date,purchase cost,purchase order,order number,Licensed To Name,Licensed to Email,expiration date,maintained,reassignable,seats,company,supplier,category,notes
Argentum Malachite Athletes Foot Relief,1aa5b0eb-79c5-40b2-8943-5472a6893c3c,"Beer, Leannon and Lubowitz",05/15/2019,$1865.34,63 ar,18334,A Legend,Legendary@gov.uk,04/27/2016,yes,true,64,"Haag, Schmidt and Farrell","Hegmann, Mohr and Cremin",Graphics Software,Sed ante. Vivamus tortor. Duis mattis egestas metus.
EOT;
$importer = new LicenseImporter($updatedCSV);
$importer->setUserId(1)
->setUpdating(true)
->import();
// At this point we should still only have one record.
$this->tester->seeNumRecords(1, 'licenses');
// But instead these.
\Log::debug($this->tester->grabRecord('licenses'));
$this->tester->seeRecord('licenses', [
'name' => 'Argentum Malachite Athletes Foot Relief',
'purchase_date' => '2019-05-15 00:00:01',
'seats' => 64,
'license_email' => 'Legendary@gov.uk',
'order_number' => '18334',
'license_name' => 'A Legend',
'expiration_date' => '2016-04-27',
'maintained' => 1,
'notes' => 'Sed ante. Vivamus tortor. Duis mattis egestas metus.',
'purchase_cost' => 1865.34,
'purchase_order' => '63 ar',
'reassignable' => 1,
'serial' => '1aa5b0eb-79c5-40b2-8943-5472a6893c3c',
]);
// License seats are soft deleted
$this->tester->seeNumRecords(64, 'license_seats', ['deleted_at' => null]);
}
public function testCustomLicenseImport()
{
$csv = <<<'EOT'
Name,Email,Username,Object name,serial num,manuf,pur date,pur cost,purc order,order num,Licensed To,Licensed Email,expire date,maint,reass,seat,comp,supplier,category,note
Helen Anderson,cspencer0@privacy.gov.au,cspencer0,Argentum Malachite Athletes Foot Relief,1aa5b0eb-79c5-40b2-8943-5472a6893c3c,"Beer, Leannon and Lubowitz",07/13/2012,$79.66,53008,386436062-5,Cynthia Spencer,cspencer0@gov.uk,01/27/2016,false,no,80,"Haag, Schmidt and Farrell","Hegmann, Mohr and Cremin",Custom Graphics Software,Sed ante. Vivamus tortor. Duis mattis egestas metus.
EOT;
$customFieldMap = [
'company' => 'Comp',
'expiration_date' => 'expire date',
'item_name' => 'Object Name',
'license_email' => 'licensed email',
'license_name' => 'licensed to',
'maintained' => 'maint',
'manufacturer' => 'manuf',
'notes' => 'note',
'order_number' => 'Order Num',
'purchase_cost' => 'Pur Cost',
'purchase_date' => 'Pur date',
'purchase_order' => 'Purc Order',
'quantity' => 'Quan',
'reassignable' => 'reass',
'requestable' => 'Request',
'seats' => 'seat',
'serial' => 'serial num',
'category' => 'category',
];
$this->import(new LicenseImporter($csv), $customFieldMap);
$this->tester->seeRecord('licenses', [
'name' => 'Argentum Malachite Athletes Foot Relief',
'purchase_date' => '2012-07-13 00:00:01',
'seats' => 80,
'license_email' => 'cspencer0@gov.uk',
'order_number' => '386436062-5',
'license_name' => 'Cynthia Spencer',
'expiration_date' => '2016-01-27',
'maintained' => 0,
'notes' => 'Sed ante. Vivamus tortor. Duis mattis egestas metus.',
'purchase_cost' => 79.66,
'purchase_order' => '53008',
'reassignable' => 0,
'serial' => '1aa5b0eb-79c5-40b2-8943-5472a6893c3c',
]);
$this->tester->seeRecord('manufacturers', [
'name' => 'Beer, Leannon and Lubowitz',
]);
$this->tester->seeRecord('suppliers', [
'name' => 'Hegmann, Mohr and Cremin',
]);
$this->tester->seeRecord('companies', [
'name' => 'Haag, Schmidt and Farrell',
]);
$this->tester->seeNumRecords(80, 'license_seats');
}
public function testDefaultUserImport()
{
Notification::fake();
$this->signIn();
$csv = <<<'EOT'
First Name,Last Name,email,Username,Location,Phone Number,Job Title,Employee Number,Company,Department,activated
Blanche,O'Collopy,bocollopy0@livejournal.com,bocollopy0,Hinapalanan,63-(199)661-2186,Clinical Specialist,7080919053,Morar-Ward,Management,1
Jessie,Primo,,jprimo1,Korenovsk,7-(885)578-0266,Paralegal,6284292031,Jast-Stiedemann,1
EOT;
$user_importer = new UserImporter($csv);
$user_importer->sendWelcome();
$this->import($user_importer);
$this->tester->seeRecord('users', [
'first_name' => 'Blanche',
'last_name' => "O'Collopy",
'email' => 'bocollopy0@livejournal.com',
'username' => 'bocollopy0',
'phone' => '63-(199)661-2186',
'jobtitle' => 'Clinical Specialist',
'employee_num' => '7080919053',
]);
$this->tester->seeRecord('companies', [
'name' => 'Morar-Ward',
]);
$this->tester->seeRecord('departments', [
'name' => 'Management',
]);
Notification::assertSentTo(User::find(2), \App\Notifications\WelcomeNotification::class);
Notification::assertNotSentTo(User::find(3), \App\Notifications\WelcomeNotification::class);
}
private function import($importer, $mappings = null)
{
if ($mappings) {
$importer->setFieldMappings($mappings);
}
$importer->setUserId(1)
->setUpdating(false)
->setUsernameFormat('firstname.lastname')
->import();
}
}

View file

@ -1,26 +0,0 @@
<?php
use App\Models\Manufacturer;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Hash;
class ManufacturerTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
// public function testManufacturerAdd()
// {
// $manufacturers = factory(Manufacturer::class)->make();
// $values = [
// 'name' => $manufacturers->name,
// ];
// Manufacturer::create($values);
// $this->tester->seeRecord('manufacturers', $values);
// }
}

View file

@ -1,36 +0,0 @@
<?php
use App\Exceptions\CheckoutNotAllowed;
use App\Models\Asset;
use App\Models\AssetModel;
use App\Models\Category;
use App\Models\Location;
use App\Models\User;
use App\Notifications\CheckoutAssetNotification;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;
class NotificationTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testAUserIsEmailedIfTheyCheckoutAnAssetWithEULA()
{
$admin = User::factory()->superuser()->create();
Auth::login($admin);
$cat = $this->createValidCategory('asset-laptop-category', ['require_acceptance' => true]);
$model = $this->createValidAssetModel('mbp-13-model', ['category_id' => $cat->id]);
$asset = $this->createValidAsset(['model_id' => $model->id]);
$user = $this->createValidUser();
Notification::fake();
$asset->checkOut($user, 1);
Notification::assertSentTo($user, CheckoutAssetNotification::class);
}
}

View file

@ -1,511 +0,0 @@
<?php
use App\Models\Accessory;
use App\Models\Asset;
use App\Models\Component;
use App\Models\Consumable;
use App\Models\License;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
class PermissionsTest extends BaseTest
{
public function _before()
{
parent::_before();
$this->noHardware = [
'assets.view' => false,
'assets.create' => false,
'assets.edit' => false,
'assets.delete' => false,
];
$this->noLicenses = [
'licenses.view' => false,
'licenses.create' => false,
'licenses.edit' => false,
'licenses.delete' => false,
];
$this->noAccessories = [
'accessories.view' => false,
'accessories.create' => false,
'accessories.edit' => false,
'accessories.delete' => false,
];
$this->noConsumables = [
'consumables.view' => false,
'consumables.create' => false,
'consumables.edit' => false,
'consumables.delete' => false,
];
$this->noComponents = [
'components.view' => false,
'components.create' => false,
'components.edit' => false,
'components.delete' => false,
];
$this->noUsers = [
'users.view' => false,
'users.create' => false,
'users.edit' => false,
'users.delete' => false,
];
}
private $noHardware;
private $noLicenses;
private $noAccessories;
private $noConsumables;
private $noComponents;
private $noUsers;
// tests
/**
* @test
*/
public function a_user_with_no_permissions_sees_nothing()
{
$u = \App\Models\User::factory()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
// $permissions = $this->noHardware;
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_view_asset_permissions_can_view_assets()
{
$u = \App\Models\User::factory()->viewAssets()->create();
$permissions = $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
$permissions = array_merge($permissions, [
'assets.view' => true,
'assets.create' => false,
'assets.edit' => false,
'assets.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_create_asset_permissions_can_create_assets()
{
$u = \App\Models\User::factory()->createAssets()->create();
$permissions = $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
$permissions = array_merge($permissions, [
'assets.view' => false,
'assets.create' => true,
'assets.edit' => false,
'assets.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_edit_assets_permissions_can_edit_assets()
{
$u = \App\Models\User::factory()->editAssets()->create();
$permissions = $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
$permissions = array_merge($permissions, [
'assets.view' => false,
'assets.create' => false,
'assets.edit' => true,
'assets.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_delete_assets_permissions_can_delete_assets()
{
$u = \App\Models\User::factory()->deleteAssets()->create();
$permissions = $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
$permissions = array_merge($permissions, [
'assets.view' => false,
'assets.create' => false,
'assets.edit' => false,
'assets.delete' => true,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_view_licenses_permissions_can_view_licenses()
{
$u = \App\Models\User::factory()->viewLicenses()->create();
$permissions = $this->noHardware + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
$permissions = array_merge($permissions, [
'licenses.view' => true,
'licenses.create' => false,
'licenses.edit' => false,
'licenses.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_create_licenses_permissions_can_create_licenses()
{
$u = \App\Models\User::factory()->createLicenses()->create();
$permissions = $this->noHardware + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
$permissions = array_merge($permissions, [
'licenses.view' => false,
'licenses.create' => true,
'licenses.edit' => false,
'licenses.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_edit_licenses_permissions_can_edit_licenses()
{
$u = \App\Models\User::factory()->editLicenses()->create();
$permissions = $this->noHardware + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
$permissions = array_merge($permissions, [
'licenses.view' => false,
'licenses.create' => false,
'licenses.edit' => true,
'licenses.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_delete_licenses_permissions_can_delete_licenses()
{
$u = \App\Models\User::factory()->deleteLicenses()->create();
$permissions = $this->noHardware + $this->noAccessories + $this->noConsumables + $this->noComponents + $this->noUsers;
$permissions = array_merge($permissions, [
'licenses.view' => false,
'licenses.create' => false,
'licenses.edit' => false,
'licenses.delete' => true,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_view_accessories_permissions_can_view_accessories()
{
$u = \App\Models\User::factory()->viewAccessories()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noConsumables + $this->noComponents + $this->noUsers;
$permissions = array_merge($permissions, [
'accessories.view' => true,
'accessories.create' => false,
'accessories.edit' => false,
'accessories.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_create_accessories_permissions_can_create_accessories()
{
$u = \App\Models\User::factory()->createAccessories()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noConsumables + $this->noComponents + $this->noUsers;
$permissions = array_merge($permissions, [
'accessories.view' => false,
'accessories.create' => true,
'accessories.edit' => false,
'accessories.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_edit_accessories_permissions_can_edit_accessories()
{
$u = \App\Models\User::factory()->editAccessories()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noConsumables + $this->noComponents + $this->noUsers;
$permissions = array_merge($permissions, [
'accessories.view' => false,
'accessories.create' => false,
'accessories.edit' => true,
'accessories.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_delete_accessories_permissions_can_delete_accessories()
{
$u = \App\Models\User::factory()->deleteAccessories()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noConsumables + $this->noComponents + $this->noUsers;
$permissions = array_merge($permissions, [
'accessories.view' => false,
'accessories.create' => false,
'accessories.edit' => false,
'accessories.delete' => true,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_view_consumables_permissions_can_view_consumables()
{
$u = \App\Models\User::factory()->viewConsumables()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noComponents + $this->noUsers;
$permissions = array_merge($permissions, [
'consumables.view' => true,
'consumables.create' => false,
'consumables.edit' => false,
'consumables.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_create_consumables_permissions_can_create_consumables()
{
$u = \App\Models\User::factory()->createConsumables()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noConsumables + $this->noComponents + $this->noUsers;
$permissions = array_merge($permissions, [
'consumables.view' => false,
'consumables.create' => true,
'consumables.edit' => false,
'consumables.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_edit_consumables_permissions_can_edit_consumables()
{
$u = \App\Models\User::factory()->editConsumables()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noComponents + $this->noUsers;
$permissions = array_merge($permissions, [
'consumables.view' => false,
'consumables.create' => false,
'consumables.edit' => true,
'consumables.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_delete_consumables_permissions_can_delete_consumables()
{
$u = \App\Models\User::factory()->deleteConsumables()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noComponents + $this->noUsers;
$permissions = array_merge($permissions, [
'consumables.view' => false,
'consumables.create' => false,
'consumables.edit' => false,
'consumables.delete' => true,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_view_users_permissions_can_view_users()
{
$u = \App\Models\User::factory()->viewUsers()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents;
$permissions = array_merge($permissions, [
'users.view' => true,
'users.create' => false,
'users.edit' => false,
'users.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_create_users_permissions_can_create_users()
{
$u = \App\Models\User::factory()->createUsers()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents;
$permissions = array_merge($permissions, [
'users.view' => false,
'users.create' => true,
'users.edit' => false,
'users.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_edit_users_permissions_can_edit_users()
{
$u = \App\Models\User::factory()->editUsers()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents;
$permissions = array_merge($permissions, [
'users.view' => false,
'users.create' => false,
'users.edit' => true,
'users.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_delete_users_permissions_can_delete_users()
{
$u = \App\Models\User::factory()->deleteUsers()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noComponents;
$permissions = array_merge($permissions, [
'users.view' => false,
'users.create' => false,
'users.edit' => false,
'users.delete' => true,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_view_components_permissions_can_view_components()
{
$u = \App\Models\User::factory()->viewComponents()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noUsers;
$permissions = array_merge($permissions, [
'components.view' => true,
'components.create' => false,
'components.edit' => false,
'components.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_create_components_permissions_can_create_components()
{
$u = \App\Models\User::factory()->createComponents()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noUsers;
$permissions = array_merge($permissions, [
'components.view' => false,
'components.create' => true,
'components.edit' => false,
'components.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_edit_components_permissions_can_edit_components()
{
$u = \App\Models\User::factory()->editComponents()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noUsers;
$permissions = array_merge($permissions, [
'components.view' => false,
'components.create' => false,
'components.edit' => true,
'components.delete' => false,
]);
$this->hitRoutes($permissions, $u);
}
/**
* @test
*/
public function a_user_with_delete_components_permissions_can_delete_components()
{
$u = \App\Models\User::factory()->deleteComponents()->create();
$permissions = $this->noHardware + $this->noLicenses + $this->noAccessories + $this->noConsumables + $this->noUsers;
$permissions = array_merge($permissions, [
'components.view' => false,
'components.create' => false,
'components.edit' => false,
'components.delete' => true,
]);
// dd($u);
$this->hitRoutes($permissions, $u);
}
private function hitRoutes(array $routes, User $user)
{
foreach ($routes as $route => $expectation) {
$this->assertEquals($user->hasAccess($route), $expectation);
}
}
}

View file

@ -1,114 +0,0 @@
<?php
use App\Models\Statuslabel;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Hash;
class StatuslabelTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
public function testRTDStatuslabelAdd()
{
$statuslabel = Statuslabel::factory()->rtd()->make();
$values = [
'name' => $statuslabel->name,
'deployable' => $statuslabel->deployable,
'pending' => $statuslabel->pending,
'archived' => $statuslabel->archived,
];
Statuslabel::create($values);
$this->tester->seeRecord('status_labels', $values);
}
public function testPendingStatuslabelAdd()
{
$statuslabel = Statuslabel::factory()->pending()->make();
$values = [
'name' => $statuslabel->name,
'deployable' => $statuslabel->deployable,
'pending' => $statuslabel->pending,
'archived' => $statuslabel->archived,
];
Statuslabel::create($values);
$this->tester->seeRecord('status_labels', $values);
}
public function testArchivedStatuslabelAdd()
{
$statuslabel = Statuslabel::factory()->archived()->make();
$values = [
'name' => $statuslabel->name,
'deployable' => $statuslabel->deployable,
'pending' => $statuslabel->pending,
'archived' => $statuslabel->archived,
];
Statuslabel::create($values);
$this->tester->seeRecord('status_labels', $values);
}
public function testOutForRepairStatuslabelAdd()
{
$statuslabel = Statuslabel::factory()->outForRepair()->make();
$values = [
'name' => $statuslabel->name,
'deployable' => $statuslabel->deployable,
'pending' => $statuslabel->pending,
'archived' => $statuslabel->archived,
];
Statuslabel::create($values);
$this->tester->seeRecord('status_labels', $values);
}
public function testOutForDiagnosticsStatuslabelAdd()
{
$statuslabel = Statuslabel::factory()->outForDiagnostics()->make();
$values = [
'name' => $statuslabel->name,
'deployable' => $statuslabel->deployable,
'pending' => $statuslabel->pending,
'archived' => $statuslabel->archived,
];
Statuslabel::create($values);
$this->tester->seeRecord('status_labels', $values);
}
public function testBrokenStatuslabelAdd()
{
$statuslabel = Statuslabel::factory()->broken()->make();
$values = [
'name' => $statuslabel->name,
'deployable' => $statuslabel->deployable,
'pending' => $statuslabel->pending,
'archived' => $statuslabel->archived,
];
Statuslabel::create($values);
$this->tester->seeRecord('status_labels', $values);
}
public function testLostStatuslabelAdd()
{
$statuslabel = Statuslabel::factory()->lost()->make();
$values = [
'name' => $statuslabel->name,
'deployable' => $statuslabel->deployable,
'pending' => $statuslabel->pending,
'archived' => $statuslabel->archived,
];
Statuslabel::create($values);
$this->tester->seeRecord('status_labels', $values);
}
}

View file

@ -1,26 +0,0 @@
<?php
use App\Models\Supplier;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Support\Facades\Hash;
class SupplierTest extends BaseTest
{
/**
* @var \UnitTester
*/
protected $tester;
// public function testSupplierAdd()
// {
// $supplier = factory(Supplier::class)->make();
// $values = [
// 'name' => $supplier->name,
// ];
// Supplier::create($values);
// $this->tester->seeRecord('suppliers', $values);
// }
}