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

chore: Calculate UI test #7052

Open
wants to merge 10 commits into
base: main
Choose a base branch
from

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'package:integration_test/integration_test.dart';

import 'desktop/document/document_test_runner_2.dart' as document_test_runner_2;
import 'desktop/grid/grid_calculations_test.dart' as grid_calculations_test;
import 'desktop/first_test/first_test.dart' as first_test;

Future<void> main() async {
Expand All @@ -13,5 +14,6 @@ Future<void> runIntegration4OnDesktop() async {
first_test.main();

document_test_runner_2.main();
grid_calculations_test.main();
// DON'T add more tests here.
}
Original file line number Diff line number Diff line change
Expand Up @@ -763,12 +763,26 @@ extension AppFlowyDatabaseTest on WidgetTester {
await tap(find.byType(CalculateCell).at(index));
await pumpAndSettle();

await tap(
find.descendant(
of: find.byType(CalculationTypeItem),
matching: find.text(type.label),
),
final calculateMenu = find
.descendant(
of: find.byType(CalculateSelector),
matching: find.byWidgetPredicate((w) => w is Scrollable),
)
.first;

final calculateType = find.descendant(
of: find.byType(CalculationTypeItem),
matching: find.text(type.label),
);

await scrollUntilVisible(
calculateType,
20,
scrollable: calculateMenu,
duration: const Duration(milliseconds: 250),
);

await tap(calculateType);
await pumpAndSettle();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,9 @@ class CalculationsBackendService {
final String viewId;

// Get Calculations (initial fetch)

Future<FlowyResult<RepeatedCalculationsPB, FlowyError>>
getCalculations() async {
final payload = DatabaseViewIdPB()..value = viewId;

return DatabaseEventGetAllCalculations(payload).send();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'package:flutter/material.dart';

import 'package:appflowy/plugins/database/application/calculations/calculation_type_ext.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/application/field/type_option/number_format_bloc.dart';
Expand All @@ -12,7 +14,6 @@ import 'package:appflowy_backend/protobuf/flowy-database2/field_entities.pbenum.
import 'package:appflowy_backend/protobuf/flowy-database2/number_entities.pb.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class CalculateCell extends StatefulWidget {
Expand Down Expand Up @@ -85,35 +86,11 @@ class _CalculateCellState extends State<CalculateCell> {
}
});

return SingleChildScrollView(
child: Column(
children: [
if (widget.calculation != null)
RemoveCalculationButton(
onTap: () => context.read<CalculationsBloc>().add(
CalculationsEvent.removeCalculation(
widget.fieldInfo.id,
widget.calculation!.id,
),
),
),
...widget.fieldInfo.fieldType.calculationsForFieldType().map(
(type) => CalculationTypeItem(
type: type,
onTap: () {
if (type != widget.calculation?.calculationType) {
context.read<CalculationsBloc>().add(
CalculationsEvent.updateCalculationType(
widget.fieldInfo.id,
type,
calculationId: widget.calculation?.id,
),
);
}
},
),
),
],
return BlocProvider.value(
value: context.read<CalculationsBloc>(),
child: CalculateSelector(
fieldInfo: widget.fieldInfo,
calculation: widget.calculation,
),
);
},
Expand All @@ -125,7 +102,7 @@ class _CalculateCellState extends State<CalculateCell> {
}

Widget _showCalculateValue(BuildContext context, String? prefix) {
prefix = prefix != null ? '$prefix ' : '';
prefix = prefix != null && prefix.isNotEmpty ? '$prefix ' : '';
final calculateValue =
'$prefix${_withoutTrailingZeros(widget.calculation!.value)}';

Expand Down Expand Up @@ -208,3 +185,49 @@ class _CalculateCellState extends State<CalculateCell> {
_ => null,
};
}

class CalculateSelector extends StatelessWidget {
const CalculateSelector({
super.key,
required this.fieldInfo,
this.calculation,
});

final FieldInfo fieldInfo;
final CalculationPB? calculation;

@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
children: [
if (calculation != null)
RemoveCalculationButton(
onTap: () => context.read<CalculationsBloc>().add(
CalculationsEvent.removeCalculation(
fieldInfo.id,
calculation!.id,
),
),
),
...fieldInfo.fieldType.calculationsForFieldType().map(
(type) => CalculationTypeItem(
type: type,
onTap: () {
if (type != calculation?.calculationType) {
context.read<CalculationsBloc>().add(
CalculationsEvent.updateCalculationType(
fieldInfo.id,
type,
calculationId: calculation?.id,
),
);
}
},
),
),
],
),
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,16 @@ use flowy_database2::entities::{
use tokio::time::sleep;

#[tokio::test]
async fn calculation_integration_test1() {
async fn get_calculate_after_edit_cell_test() {
let test = EventIntegrationTest::new().await;
test.sign_up_as_anon().await;

let workspace_id = test.get_current_workspace().await.id;
let payload = gen_csv_import_data("project.csv", &workspace_id);
let view = test.import_data(payload).await.pop().unwrap();
let database = test.open_database(&view.id).await;
let database_view_id = &view.id;

average_calculation(test, database, &view.id).await;
}

// Tests for the CalculationType::Average
// Is done on the Delay column in the project.csv
async fn average_calculation(
test: EventIntegrationTest,
database: DatabasePB,
database_view_id: &str,
) {
// Delay column is the 11th column (index 10) in the project.csv
let delay_field = database.fields.get(10).unwrap();

Expand All @@ -54,6 +45,7 @@ async fn average_calculation(
);

// Update a cell in the delay column at fourth row (3rd index)
// edit the Delay column in the project.csv
let cell_changeset = CellChangesetPB {
view_id: database_view_id.to_string(),
row_id: database.rows.get(3).unwrap().id.clone(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ impl DatabaseEditor {
.database_views
.get_or_init_view_editor(&update.view_id)
.await?;
view_editor.v_update_calculations(update).await?;
view_editor.v_edit_calculations(update).await?;
Ok(())
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -693,41 +693,7 @@ impl DatabaseViewEditor {
Ok(())
}

pub async fn v_update_calculate(&self, field_id: &str) -> Option<()> {
let field = self.delegate.get_field(field_id).await?;
let cal = self
.delegate
.get_calculation(&self.view_id, &field.id)
.await?;

let cells = self
.delegate
.get_cells_for_field(&self.view_id, field_id)
.await
.into_iter()
.flat_map(|row_cell| row_cell.cell.map(Arc::new))
.collect::<Vec<_>>();

let changes = self
.calculations_controller
.handle_cells_changed(&field, &cal, cells)
.await;

if !changes.is_empty() {
let notification = CalculationChangesetNotificationPB::from_update(&self.view_id, changes);
if let Err(_err) = self
.notifier
.send(DatabaseViewChanged::CalculationValueNotification(
notification,
))
{
error!("Failed to send CalculationValueNotification");
}
}

None
}

#[instrument(level = "trace", skip_all)]
pub async fn v_calculate_rows(&self, fields: Vec<Field>, rows: Vec<Arc<Row>>) -> FlowyResult<()> {
let mut updates = vec![];
// Filter fields to only those with calculations
Expand Down Expand Up @@ -768,6 +734,7 @@ impl DatabaseViewEditor {
}

// Send notification if updates were made
trace!("Calculations updates: {:?}", updates);
if !updates.is_empty() {
let notification = CalculationChangesetNotificationPB::from_update(&self.view_id, updates);
if let Err(_err) = self
Expand Down Expand Up @@ -798,10 +765,42 @@ impl DatabaseViewEditor {
self.delegate.get_all_calculations(&self.view_id).await
}

pub async fn v_update_calculations(
&self,
params: UpdateCalculationChangesetPB,
) -> FlowyResult<()> {
pub async fn v_update_calculate(&self, field_id: &str) -> Option<()> {
let field = self.delegate.get_field(field_id).await?;
let cal = self
.delegate
.get_calculation(&self.view_id, &field.id)
.await?;

let cells = self
.delegate
.get_cells_for_field(&self.view_id, field_id)
.await
.into_iter()
.flat_map(|row_cell| row_cell.cell.map(Arc::new))
.collect::<Vec<_>>();

let changes = self
.calculations_controller
.handle_cells_changed(&field, &cal, cells)
.await;

if !changes.is_empty() {
let notification = CalculationChangesetNotificationPB::from_update(&self.view_id, changes);
if let Err(_err) = self
.notifier
.send(DatabaseViewChanged::CalculationValueNotification(
notification,
))
{
error!("Failed to send CalculationValueNotification");
}
}

None
}

pub async fn v_edit_calculations(&self, params: UpdateCalculationChangesetPB) -> FlowyResult<()> {
let calculation_id = params
.calculation_id
.unwrap_or_else(gen_database_calculation_id);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,38 @@
use std::sync::Arc;

use crate::database::calculations_test::script::DatabaseCalculationTest;
use crate::database::database_editor::{DatabaseEditorTest, FilterRowChanged};
use collab_database::fields::Field;
use flowy_database2::entities::{CalculationType, FieldType, UpdateCalculationChangesetPB};
use flowy_database2::entities::{
CalculationType, FieldType, NumberFilterConditionPB, NumberFilterPB, UpdateCalculationChangesetPB,
};
use lib_infra::box_any::BoxAny;

#[tokio::test]
async fn calculations_test() {
let mut test = DatabaseCalculationTest::new().await;
async fn calculate_with_filter_test() {
let mut test = DatabaseEditorTest::new_grid().await;
let row_count = test.rows.len();
let expected = 1;
// let sub = test.sdk.notification_sender.subscribe().await.unwrap();

test
.create_data_filter(
None,
FieldType::Number,
BoxAny::new(NumberFilterPB {
condition: NumberFilterConditionPB::Equal,
content: "1".to_string(),
}),
Some(FilterRowChanged {
showing_num_of_rows: 0,
hiding_num_of_rows: row_count - expected,
}),
)
.await;
}

#[tokio::test]
async fn insert_delete_calculate_test() {
let mut test = DatabaseEditorTest::new_grid().await;

let expected_sum = 25.00;
let expected_min = 1.00;
Expand Down Expand Up @@ -89,7 +114,7 @@ async fn calculations_test() {

#[tokio::test]
async fn calculations_empty_test() {
let mut test = DatabaseCalculationTest::new().await;
let mut test = DatabaseEditorTest::new_grid().await;

let view_id = &test.view_id();
let text_fields = test
Expand Down Expand Up @@ -128,7 +153,7 @@ async fn calculations_empty_test() {

#[tokio::test]
async fn calculations_non_empty_test() {
let mut test = DatabaseCalculationTest::new().await;
let mut test = DatabaseEditorTest::new_grid().await;

let view_id = &test.view_id();
let text_fields = test
Expand Down Expand Up @@ -167,7 +192,7 @@ async fn calculations_non_empty_test() {

#[tokio::test]
async fn calculations_count_test() {
let mut test = DatabaseCalculationTest::new().await;
let mut test = DatabaseEditorTest::new_grid().await;

let view_id = &test.view_id();
let text_fields = test
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
mod calculation_test;
mod script;
Loading
Loading