Files
inventree-app/test/setup.dart
T
Oliver c75403b3ed Session auth (#904)
* use session auth rather than token auth

* Add unit tests for login

* Ensure user cannot reuse login after logout

* handle logout mid session

* Additional unit tests

* ensure sensitive data is redacted from sentry

* Handle session disconnect

* Additional tweaks

* Update pubspec.lock

* Update release_notes.md

* Bump version number

* Adjust login button

* Clear stored session when host changes

* Improved redacting of sensitive info

* Improved handling of local session storage

* prevent failed migration from logging as complete

* Fix for error raised in overlapping requests

* replace userInfo on successful response

* handle empty response

* Improved session comparison

* Add UI testing
2026-11-02 19:15:27 +11:00

160 lines
4.6 KiB
Dart

import "package:flutter/services.dart";
import "package:flutter_test/flutter_test.dart";
import "package:package_info_plus/package_info_plus.dart";
import "package:inventree/api.dart";
import "package:inventree/auth/auth_manager.dart";
import "package:inventree/auth/auth_method.dart";
import "package:inventree/user_profile.dart";
// This is the same as the following issue except it keeps the http client
// TestWidgetsFlutterBinding.ensureInitialized();
class CustomBinding extends AutomatedTestWidgetsFlutterBinding {
@override
bool get overrideHttpClient => false;
}
// Secure storage operations (e.g. "write", "delete") which should fail,
// to test handling of storage errors
final Set<String> secureStorageFailures = {};
void setupTestEnv() {
// Uses custom binding to not override the http client
CustomBinding();
// Package information is used when building error reports
PackageInfo.setMockInitialValues(
appName: "InvenTree",
packageName: "inventree.inventree_app",
version: "0.0.0",
buildNumber: "0",
buildSignature: "",
);
// Mock the path provider
const MethodChannel channel = MethodChannel(
"plugins.flutter.io/path_provider",
);
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (MethodCall methodCall) async {
return ".";
});
// Mock secure storage (used for storing profile session cookies) with a
// simple in-memory map, since there's no real platform keychain available
// in the test harness
final Map<String, String> secureStorageMock = {};
const MethodChannel secureStorageChannel = MethodChannel(
"plugins.it_nomads.com/flutter_secure_storage",
);
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(secureStorageChannel, (
MethodCall methodCall,
) async {
if (secureStorageFailures.contains(methodCall.method)) {
throw PlatformException(
code: "SecureStorageFailure",
message: "Simulated secure storage failure",
);
}
final Map<dynamic, dynamic> args =
(methodCall.arguments as Map<dynamic, dynamic>?) ?? {};
final String? key = args["key"] as String?;
switch (methodCall.method) {
case "write":
secureStorageMock[key!] = args["value"] as String;
return null;
case "read":
return secureStorageMock[key];
case "containsKey":
return secureStorageMock.containsKey(key);
case "delete":
secureStorageMock.remove(key);
return null;
case "deleteAll":
secureStorageMock.clear();
return null;
case "readAll":
return secureStorageMock;
default:
return null;
}
});
}
// Accessors for default testing values
const String testServerAddress = "http://localhost:8000/";
const String testServerName = "Test Server";
const String testUsername = "admin";
const String testPassword = "inventree";
/*
* Login to the server with the given profile (establishing a session)
*/
Future<bool> loginProfile({
UserProfile? profile,
String username = testUsername,
String password = testPassword,
}) async {
profile ??= await UserProfileDBManager().getProfileByName(testServerName);
assert(profile != null);
final result = await InvenTreeAuth().beginLogin(
profile!,
PasswordAuthMethod(username, password),
);
return result.authenticated;
}
/*
* Setup a valid profile, and return it
*/
Future<UserProfile> setupServerProfile({
bool select = true,
bool login = false,
}) async {
// Setup a valid server profile
UserProfile? profile = await UserProfileDBManager().getProfileByName(
testServerName,
);
if (profile == null) {
// Profile does not already exist - create it!
bool result = await UserProfileDBManager().addProfile(
UserProfile(server: testServerAddress, name: testServerName),
);
assert(result);
}
profile = await UserProfileDBManager().getProfileByName(testServerName);
assert(profile != null);
if (select) {
assert(await UserProfileDBManager().selectProfileByName(testServerName));
}
if (login && !profile!.hasSession) {
final bool result = await loginProfile(profile: profile);
assert(result);
assert(profile.hasSession);
}
return profile!;
}
/*
* Complete all steps necessary to login to the server
*/
Future<void> connectToTestServer() async {
// Setup profile, and login as necessary
final profile = await setupServerProfile(login: true);
// Connect to the server
assert(await InvenTreeAPI().connectToServer(profile));
}