Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

⬆️ ☁️ Upload Service -- rewrite and testing #1053

Merged
merged 34 commits into from
Oct 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
728a7f5
rename the angular service with ng prefix
Sep 28, 2023
2049c59
start uploadService.ts and tests
Sep 28, 2023
7de8828
add logError fcn to Logger.ts
Sep 28, 2023
9606f57
change the name in index.js
Sep 29, 2023
eaf4be5
adapt promise handling to async/await
Sep 29, 2023
838f6da
adding user-input component of upload to profile
Sep 29, 2023
7a7cb29
Merge remote-tracking branch 'upstream/onboarding_routing_sept_2023' …
Sep 29, 2023
43b1b98
resolve leftover issue from merge
Sep 29, 2023
5a8d248
correct message in reason modal
Oct 2, 2023
c2dc6e9
upload service working
Oct 2, 2023
a5451e9
resolve errors
Oct 2, 2023
a7d4ec3
set up testing for uploadService
Oct 3, 2023
98a7dbd
Merge remote-tracking branch 'upstream/onboarding_routing_sept_2023' …
Oct 3, 2023
e49d39b
Merge remote-tracking branch 'JGreenlee/rewrite-services-sept2023' in…
Oct 3, 2023
0e3a0e5
more mocks for testing
Oct 4, 2023
019d715
working mocks and tests!
Oct 4, 2023
d3c0829
fix bad merge conflifct
Oct 4, 2023
e3ebe85
restored alerts, added mock, added comments
Oct 5, 2023
e0dd682
remove old angular upload service
Oct 5, 2023
51533ef
update fetch POST
Oct 5, 2023
69ada00
restore url encoding for additional params
Oct 6, 2023
75aeb48
update mock
Oct 6, 2023
7e85ea2
Merge branch 'service_rewrite_2023' into services_rewrite
JGreenlee Oct 16, 2023
4f3d9fb
fix indentations
Oct 16, 2023
185813f
better object declaration
Oct 16, 2023
655ddda
additional indentation improvement
Oct 16, 2023
4026423
remove logError
Oct 16, 2023
0c1bac8
remove uneeded code
Oct 16, 2023
86fe118
correct outdated comments
Oct 19, 2023
cac185f
add comments and timeout
Oct 19, 2023
4b148c2
fix location of timeout
Oct 19, 2023
d8a3b33
revert uploadSample json file
Oct 19, 2023
1afe3d0
Merge remote-tracking branch 'upstream/service_rewrite_2023' into ser…
Oct 19, 2023
f2f0cfb
FETCH -> GET to match HTTP request types
shankari Oct 20, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions www/__mocks__/cordovaMocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ export const mockGetAppVersion = () => {
window['cordova'].getAppVersion = mockGetAppVersion;
}

export const mockFile = () => {
window['cordova'].file = { "dataDirectory" : "../path/to/data/directory",
"applicationStorageDirectory" : "../path/to/app/storage/directory"};
}

export const mockBEMUserCache = () => {
const _cache = {};
const messages = [];
Expand Down
23 changes: 23 additions & 0 deletions www/__mocks__/fileSystemMocks.ts
Abby-Wheelis marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
export const mockFileSystem = () => {
window['resolveLocalFileSystemURL'] = function (parentDir, handleFS) {
const fs = {
filesystem:
{
root:
{
getFile: (path, options, onSuccess) => {
let fileEntry = {
file: (handleFile) => {
let file = new File(["this is a mock"], "loggerDB");
handleFile(file);
}
}
onSuccess(fileEntry);
}
}
}
}
console.log("in mock, fs is ", fs, " get File is ", fs.filesystem.root.getFile);
handleFS(fs);
}
}
52 changes: 52 additions & 0 deletions www/__tests__/uploadService.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
//this is never used in production right now
//however, tests are still important to make sure the code works
//at some point we hope to restore this functionality

import {uploadFile} from "../js/control/uploadService";
import { mockLogger } from '../__mocks__/globalMocks';
import { mockDevice, mockGetAppVersion, mockCordova, mockFile } from "../__mocks__/cordovaMocks";
import { mockFileSystem } from "../__mocks__/fileSystemMocks";

mockDevice();
mockGetAppVersion();
mockCordova();

mockLogger();
mockFile(); //mocks the base directory
mockFileSystem(); //comnplex mock, allows the readDBFile to work in testing
shankari marked this conversation as resolved.
Show resolved Hide resolved

//use this message to verify that the post went through
let message = "";

//each have a slight delay to mimic a real fetch request
global.fetch = (url: string, options: { method: string, headers: {}, body: string }) => new Promise((rs, rj) => {
//if there's options, that means there is a post request
if (options) {
message = "sent " + options.method + options.body + " for " + url;
setTimeout(() => {
rs('sent ' + options.method + options.body + ' to ' + url);
}, 100);
}
//else it is a get request
else {
setTimeout(() => rs({
json: () => new Promise((rs, rj) => {
setTimeout(() => rs('mock data for ' + url), 100);
})
}));
}
}) as any;

window.alert = (message) => {
console.log(message);
}

//very basic tests - difficult to do too much since there's a lot of mocking involved
it('posts the logs to the configured database', async () => {
let posted = await uploadFile("loggerDB", "HelloWorld");
expect(message).toEqual(expect.stringContaining("HelloWorld"));
expect(message).toEqual(expect.stringContaining("POST"));
posted = await uploadFile("loggerDB", "second test");
expect(message).toEqual(expect.stringContaining("second test"));
expect(message).toEqual(expect.stringContaining("POST"));
}, 10000);
1 change: 0 additions & 1 deletion www/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import './js/survey/enketo/answer.js';
import './js/survey/enketo/enketo-trip-button.js';
import './js/survey/enketo/enketo-add-note-button.js';
import './js/control/emailService.js';
import './js/control/uploadService.js';
import './js/metrics-factory.js';
import './js/metrics-mappings.js';
import './js/plugin/logger.ts';
39 changes: 33 additions & 6 deletions www/js/control/ProfileSettings.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState, useEffect, useContext, useRef } from "react";
import { Modal, StyleSheet, ScrollView } from "react-native";
import { Dialog, Button, useTheme, Text, Appbar, IconButton } from "react-native-paper";
import { Dialog, Button, useTheme, Text, Appbar, IconButton, TextInput } from "react-native-paper";
import { getAngularService } from "../angular-react-helper";
import { useTranslation } from "react-i18next";
import ExpansionSection from "./ExpandMenu";
Expand All @@ -12,8 +12,9 @@ import ReminderTime from "./ReminderTime"
import useAppConfig from "../useAppConfig";
import AlertBar from "./AlertBar";
import DataDatePicker from "./DataDatePicker";
import AppStatusModal from "./AppStatusModal";
import PrivacyPolicyModal from "./PrivacyPolicyModal";

import {uploadFile} from "./uploadService";
import ActionMenu from "../components/ActionMenu";
import SensedPage from "./SensedPage"
import LogPage from "./LogPage";
Expand All @@ -35,7 +36,6 @@ const ProfileSettings = () => {

//angular services needed
const CarbonDatasetHelper = getAngularService('CarbonDatasetHelper');
const UploadHelper = getAngularService('UploadHelper');
const EmailHelper = getAngularService('EmailHelper');
const NotificationScheduler = getAngularService('NotificationScheduler');
const ControlHelper = getAngularService('ControlHelper');
Expand All @@ -57,6 +57,7 @@ const ProfileSettings = () => {
const [consentVis, setConsentVis] = useState(false);
const [dateDumpVis, setDateDumpVis] = useState(false);
const [privacyVis, setPrivacyVis] = useState(false);
const [uploadVis, setUploadVis] = useState(false);
const [showingSensed, setShowingSensed] = useState(false);
const [showingLog, setShowingLog] = useState(false);
const [editSync, setEditSync] = useState(false);
Expand All @@ -72,6 +73,7 @@ const ProfileSettings = () => {
const [uiConfig, setUiConfig] = useState({});
const [consentDoc, setConsentDoc] = useState({});
const [dumpDate, setDumpDate] = useState(new Date());
const [uploadReason, setUploadReason] = useState("");
const appVersion = useRef();

let carbonDatasetString = t('general-settings.carbon-dataset') + ": " + CarbonDatasetHelper.getCurrentCarbonDatasetCode();
Expand Down Expand Up @@ -219,8 +221,12 @@ const ProfileSettings = () => {

//methods that control the settings
const uploadLog = function () {
UploadHelper.uploadFile("loggerDB")
};
if(uploadReason != "") {
let reason = uploadReason;
uploadFile("loggerDB", reason);
setUploadVis(false);
}
}

const emailLog = function () {
// Passing true, we want to send logs
Expand Down Expand Up @@ -329,7 +335,7 @@ const ProfileSettings = () => {
let logUploadSection;
console.debug("appConfg: support_upload:", appConfig?.profile_controls?.support_upload);
if (appConfig?.profile_controls?.support_upload) {
logUploadSection = <SettingRow textKey="control.upload-log" iconName="cloud" action={uploadLog}></SettingRow>;
logUploadSection = <SettingRow textKey="control.upload-log" iconName="cloud" action={() => setUploadVis(true)}></SettingRow>;
}

let timePicker;
Expand Down Expand Up @@ -414,6 +420,27 @@ const ProfileSettings = () => {
{/* force state sheet */}
<ActionMenu vis={forceStateVis} setVis={setForceStateVis} title={"Force State"} actionSet={stateActions} onAction={onSelectState} onExit={() => {}}></ActionMenu>

{/* upload reason input */}
<Modal visible={uploadVis} onDismiss={() => setUploadVis(false)}
transparent={true}>
<Dialog visible={uploadVis}
shankari marked this conversation as resolved.
Show resolved Hide resolved
onDismiss={() => setUploadVis(false)}
style={settingStyles.dialog(colors.elevation.level3)}>
<Dialog.Title>{t('upload-service.upload-database', {db: "loggerDB"})}</Dialog.Title>
<Dialog.Content>
<TextInput label="Reason"
value={uploadReason}
onChangeText={uploadReason => setUploadReason(uploadReason)}
placeholder={t('upload-service.please-fill-in-what-is-wrong')}>
</TextInput>
</Dialog.Content>
<Dialog.Actions>
<Button onPress={() => setUploadVis(false)}>{t('general-settings.cancel')}</Button>
<Button onPress={() => uploadLog()}>Upload</Button>
</Dialog.Actions>
</Dialog>
</Modal>

{/* opcode viewing popup */}
<PopOpCode visibilityValue = {opCodeVis} setVis = {setOpCodeVis} tokenURL = {"emission://login_token?token="+authSettings.opcode} action={() => shareQR(authSettings.opcode)}></PopOpCode>

Expand Down
171 changes: 0 additions & 171 deletions www/js/control/uploadService.js

This file was deleted.

Loading