Error when upload excel file

Hello, During upload excel file when number of VUs increases something happen

TypeError: Cannot read property ‘filename’ of undefined
running at 404 - resource not found

What can i do to handle this error.



Could you share an anonymized version of your script?

1 Like
import http from 'k6/http';
import { sleep, check, group } from 'k6';
import { randomIntBetween } from 'https://jslib.k6.io/k6-utils/1.2.0/index.js';
import { FormData } from "https://jslib.k6.io/formdata/0.0.2/index.js";
import { Counter } from 'k6/metrics';

const memberUploadCount = new Counter('success_member_upload_count');
const memberUploadFailCount = new Counter('fails_member_upload_count');
let dummyFarmersExcelFile = open('./uploads/ndugu.xls'); 
let token;
let csrfToken;
const BASE_URL = 'xxxxxxxxxxxxxxxxxxx';
const USERNAME = 'joshua.ngondya';
const PASSWORD = 'Tfra@123456';

// upload members data
// 1. Prepare uploads  data using formData object;
const formData = new FormData();
formData.append('file', http.file(dummyFarmersExcelFile, 'ndugu.xls', 'application/vnd.ms-excel'));
formData.append('region_filter', '5');
formData.append('district_filter', '90');
formData.append('ward_filter', '2161');
formData.append('village_id', '10215');
formData.append('primary_society_id', '10226');


export const options = {
    insecureSkipTLSVerify: true,
    scenarios: {
        smoke_test: {
            vus: 5,
            duration: '3m',
            executor: 'constant-vus',
            exec: 'uploadMembersByExcel'
        },
        upload_members_const_rps: {
            executor: 'constant-arrival-rate',
            // How long the test lasts
            duration: '5m',
            // How many iterations per timeUnit
            rate: 50,
            // Start `rate` iterations per second
            timeUnit: '1s',
            // Pre-allocate VUs
            preAllocatedVUs: 100,
            startTime: '5m',
            exec: 'uploadMembersByExcel',
            maxVUs: 200
        }
    }
};


export function uploadMembersByExcel() {
    group('Navigate to login page', function () {
        navigateToLogin();
        postLogin();
    });
    group('Upload members from excel', function () {
        navigateFarmerImport();
        uploadsFarmer();
    });
}


export function navigateToLogin() {
    const loginPage = http.get(`${BASE_URL}/login`, {
        headers: {
            host: 'xx.xx.xx.xx',
            'user-agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:104.0) Gecko/20100101 Firefox/104.0',
            accept:
            'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
            'accept-language': 'en-US,en;q=0.5',
            'accept-encoding': 'gzip, deflate, br',
            connection: 'keep-alive',
            cookie:
            'XSRF-TOKEN=SECRET',
            'upgrade-insecure-requests': '1',
            'sec-fetch-dest': 'document',
            'sec-fetch-mode': 'navigate',
            'sec-fetch-site': 'none',
            'sec-fetch-user': '?1',
            'sec-gpc': '1',
        }, 
    });

    token = loginPage.html().find('input[name=_token]').attr('value');
    console.log('csrf token: ' + token);
    sleep(randomIntBetween(1,5));
}

export function postLogin() {
    const postLoginForm = http.post(`${BASE_URL}/login`, JSON.stringify({
        username: USERNAME,
        password: PASSWORD,
        _token: token
    }), {
        headers: {
            'Content-Type': 'application/json',
        }, 
        redirects: 2
    });

    check(postLoginForm, {
        'is post login form': res => res.status === 200
    });

    sleep(randomIntBetween(1,5));
}

export function navigateFarmerImport() {
        const importFarmerPage = http.get(`${BASE_URL}/farmers-import-form`);
        csrfToken = importFarmerPage.html().find('head meta[name="csrf-token"]').attr('content');

        check('csrf token exist', {
            'is csrf token available': res => res !== undefined && res !== ''
        });

        check(importFarmerPage, {
            'is importFarmerPage status 200': res => res.status === 200
        });
        console.log('Navigate Farmer Import ' + importFarmerPage.status);
        sleep(randomIntBetween(3,6));
}

export function uploadsFarmer() {
        formData.append('_token', csrfToken);

        const multipartHeader = { 
            'Content-Type': 'multipart/form-data; boundary=' + formData.boundary,
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
            'Connection': 'keep-alive'
        };

        const importFarmers = http.post(`${BASE_URL}/import-farmers`, formData.body(), {headers: multipartHeader, redirects: 2});

        console.log('Navigate Member Upload ' + importFarmers.status);

        if (importFarmers.status === 200) {
            memberUploadCount.add(1);
        } else {
            memberUploadFailCount.add(1);
        }

        console.log('import members ' + importFarmers.status);
        check(importFarmers, {
            'is import members uploaded 200': res => res.status === 200
        });

        sleep(randomIntBetween(1,5));
}

export function teardown() {
    logout();
}

export function logout() {
    const headers = {
        'Content-Type': 'application/json'
    };
    const homePage = http.get(`${BASE_URL}`);
    const logoutToken = homePage.html().find('input[name=_token]').attr('value');
    const postLogout = http.post(`${BASE_URL}/logout`, JSON.stringify({
        _token: logoutToken
    }), {headers: headers});
    console.log(postLogout);
    check(postLogout, {
        'is logout success': res => res.status === 200
    });
}

Hi @Elibarick

Can you share a couple of things:

  • Where do you see the error, always while running the smoke_test or the upload_members_const_rps as well?
  • Can you share the complete error in text format (not screenshot), and what line/s it refers to in your script? Is the error appearing in navigateFarmerImport() or uploadsFarmer()? If we can see at what line is failing, troubleshooting will be easier.

My usual approach is to simplify the script to the point it fails, removing as much as possible (only the scenario that fails, reduce iterations to understand when it fails…). I was trying to build a simpler version, but this one does not fail and I’m not sure what part in your script causes the failure:

import http from 'k6/http';
import { check } from 'k6';
import { FormData } from 'https://jslib.k6.io/formdata/0.0.2/index.js';

export const options = {
    insecureSkipTLSVerify: true,
    scenarios: {
        smoke_test: {
            vus: 5,
            duration: '3m',
            executor: 'constant-vus',
            exec: 'uploadMembersByExcel'
        },
        upload_members_const_rps: {
            executor: 'constant-arrival-rate',
            duration: '5m',
            rate: 50,
            timeUnit: '1s',
            preAllocatedVUs: 100,
            startTime: '5m',
            exec: 'uploadMembersByExcel',
            maxVUs: 200
        }
    }
};

const txt = open('./file.txt');

export function uploadMembersByExcel() {
    const fd = new FormData();
    fd.append('someTextField', 'someValue');
    fd.append('anotherTextField', 'anotherValue');
    fd.append('text', http.file(txt, 'file.txt', 'text/plain'));

    const res = http.post('https://httpbin.test.k6.io/post', fd.body(), {
        headers: { 'Content-Type': 'multipart/form-data; boundary=' + fd.boundary },
    });
    check(res, {
        'is status 200': (r) => r.status === 200,
    });
}

Thanks for the additional context!

Hi @eyeveebe It wasn’t failing for small number VUs but when i updates number VUs to 50 error appear with message “Authorization token: “Cannot read property ‘filename’ of undefined” source=console” apprear in some requests when upload request called.

Hi @Elibarick

Apologies for the delay in getting back to you.

It would be best if you looked at what you are trying to load test, and try to simplify your scenarios. For example:

  1. If you are trying to load test getting a token, how many concurrent users will be able to get one, device a scenario for that only. And I would not mix it with the upload. Those two endpoints might have different requirements.
  2. For the upload endpoint, try to get the token during the setup for all VUs, and reuse it. So you can test the upload alone. And again see if that is hitting a bottleneck and where the issue is.

I imagine, based on the error you shared, that the HTTP responses might not contain a valid reply and the check fails. But I can’t say for sure since you do not share at what lines the errors happen in your actual script.

If you cant’t figure this out, seeing at what line/s it fails in the script, I would log the responses using console.log(), so you can see what is being returned when you see the failures. Or use http debugging and investigate what happens around that request.

As to what causes this when you increase the number of VUs it can be both on the system under test (SUT) side, or the load generator. Have you reviewed both your SUT logs & metrics, and the load generator, to see if there is a bottleneck that causes requests to fail, and where the bottleneck is?

Some help in Running large tests, and potentially in Unable to connect to gRPC server running locally - #7 by mstoykov.

And many thanks for helping other users in the forum, much appreciated :grinning:

Cheers!