Add a safeguard for ExPlat assignment requests to make sure a user either has an anon_id defined and not empty

This commit is contained in:
Chi-Hsuan Huang 2022-05-03 14:54:23 +08:00
parent 4c9097d639
commit 6c8ee08f19
4 changed files with 34 additions and 3 deletions

View File

@ -52,6 +52,12 @@ export const fetchExperimentAssignment = async ( {
`Tracking is disabled, can't fetch experimentAssignment`
);
}
if ( ! anonId ) {
throw new Error(
`Can't fetch experiment assignment without an anonId or auth, please initialize anonId first or use fetchExperimentAssignmentWithAuth instead.`
);
}
return await window.fetch(
`https://public-api.wordpress.com/wpcom/v2/experiments/${ EXPLAT_VERSION }/assignments/woocommerce?${ getRequestQueryString(
{

View File

@ -41,6 +41,14 @@ describe( 'fetchExperimentAssignment', () => {
'https://public-api.wordpress.com/wpcom/v2/experiments/0.1.0/assignments/woocommerce?anon_id=abc&test=test'
);
} );
it( 'should throw error when anonId is empty', async () => {
const fetchPromise = fetchExperimentAssignment( {
experimentId: '123',
anonId: null,
} );
await expect( fetchPromise ).rejects.toThrowError();
} );
} );
describe( 'fetchExperimentAssignmentWithAuth', () => {

View File

@ -122,6 +122,10 @@ final class Experimental_Abtest {
// Request as anonymous user.
if ( ! isset( $response ) ) {
if ( ! isset( $args['anon_id'] ) || empty( $args['anon_id'] ) ) {
return new \WP_Error( 'invalid_anon_id', 'anon_id must be an none empty string.' );
}
$url = add_query_arg(
$args,
sprintf(

View File

@ -61,9 +61,9 @@ class Experimental_Abtest_Test extends WC_Unit_Test_Case {
);
}
/**
* Tests retrieve the test variation when consent is false
*/
/**
* Tests retrieve the test variation when consent is false
*/
public function test_get_variation() {
delete_transient( 'abtest_variation_control' );
add_filter(
@ -90,4 +90,17 @@ class Experimental_Abtest_Test extends WC_Unit_Test_Case {
'treatment'
);
}
/**
* Tests return request_assignment wp error when anon_id is empty
*/
public function test_request_assignment_returns_wp_error_when_anon_id_is_empty() {
$exp = new Experimental_Abtest( '', 'platform', true );
$this->assertEquals(
is_wp_error( $exp->request_assignment( 'test_experiment_name' ) ),
true
);
}
}