Location>code7788 >text

Playwright+Python] Tutorial Series (VII) Using Playwright for API Interface Testing

Popularity:785 ℃/2024-08-05 21:49:45

playwrightIt's also possible to do interface testing, but personally I still don't haverequestsThe library is powerful, but andseleniumIn comparison, it is slightly better, after all, it supports API login, which means that you can directly call the interface operation without interaction.

How does it work?

Since it is the test of the API, then certainly do not engage in UI automation that set, engage in what browser interaction, that is called what API testing, pure bullshit.

It's not like some bloggers are even lazier and just post the official example, do I use you to copy it again for me?

Come below, explain how to do API testing using playwright?

Instantiating the request object

The sample code is as follows:

.new_context()

That's right, after instantiation, it's all about tuning the API, see, it's not really that hard is it?

practical experience

Here I wrote my own student management system to do a demonstration of some of the interfaces, and some common api to explain the code examples are written in synchronous way.

1. GET request

Examples are shown below:

def testQueryStudent(playwright: Playwright):
    """
    Inquiry Student
    """
    url = 'http://localhost:8090/studentFindById'
    param = {
        'id': 105
    }
    request_context = .new_context()
    response = request_context.get(url=url, params=param)
    assert
    assert ()
    print('\n', ())

Effect:

2、POST request

Sample code:

def testAddStudent(playwright: Playwright):
    """
    Additional students
    :return:
    """
    url = 'http://localhost:8090/studentAdd'
    request_body = {
        "className": "banji",
        "courseName": "wuli",
        "email": "ales@",
        "name": "ales",
        "score": 70,
        "sex": "boy",
        "studentId": "92908290"
    }
    header = {"Content-Type": "application/json"}
    request_context = .new_context()
    response = request_context.post(url=url, headers=header, data=request_body)
    assert
    assert ()
    print('\n', ())

Effect:

3. PUT request

Sample code:

def testUpdateStudents(playwright: Playwright):
    """
    Modification of students
    """
    url = 'http://localhost:8090/studentUpdate/100'
    param = {
        'studentId': "id" + str(100),
        'name': "name" + str(100),
        'score': 100,
        "sex": "girl",
        "className": "class" + str(100),
        "courseName": "course" + str(100),
        "email": str(100) + "email@"

    }
    request_context = .new_context()
    response = request_context.put(url=url, form=param)
    assert
    assert ()
    print('\n', ())

Effect:

4. DELETE request

Sample code:

def testDeleteStudents(playwright: Playwright):
    """
    Delete Student
    """
    url = 'http://localhost:8090/studentDelete/' + str(105)
    request_context = .new_context()
    response = request_context.delete(url=url)
    assert
    assert ()
    print('\n', ())

Effect:

5. Uploading files

This is a special case, according to the official method, I really can not succeed, has always been prompted on the upload file can not be empty, but also less than why, the results I used an alternative, that is, packet capture simulation of the construction of the input parameter, before success, but also the twists and turns ah.

Sample code:

def test_upload_file(playwright: Playwright):
    '''
    Uploading files
    :param playwright:
    :return:
    '''
    # Creating a Request Context
    request_context = .new_context()

    # 定义Uploading files的URL
    upload_url = "http://localhost:8090/fileUpload"

    # file path
    file_path = "d:/"

    # Get the file name andMIMEtypology
    filename = file_path.split('/')[-1]
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type:
        mime_type = 'application/octet-stream'

    # Read the contents of the file
    with open(file_path, 'rb') as file:
        file_content = ()

    # tectonic (geology)multipart/form-databoundary string
    boundary = '---------------------' + str((1e28, 1e29 - 1))

    # tectonic (geology)requesting体
    body = (
        f'--{boundary}\r\n'
        f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'
        f'Content-Type: {mime_type}\r\n\r\n'
        f'{file_content.decode("utf-8") if mime_type.startswith("text/") else file_content.hex()}'
        f'\r\n--{boundary}--\r\n'
    ).encode('utf-8')

    # Setting the request header
    headers = {
        'Content-Type': f'multipart/form-data; boundary={boundary}',
    }
    # propose sth (for the first time)POSTrequesting
    response = request_context.post(upload_url, data=body, headers=headers)

    # Check response
    assert == 200, f"Upload failed with status: {}"
    assert
    assert ()
    print('\n', ())

Effect:

Official Writeup:

# Read the contents of the file
with open(file_path, 'rb') as file:
    file_content = ()
    response = request_context.post(upload_url, multipart={
        "fileField": {
            "name": "",
            "mimeType": "text/plain",
            "buffer": file_content,
        }
    })
print('\n', ())

Effect:

The official way to write, I do not know why, there are warriors know, but also please help to give an example, I am grateful ah!

put at the end

I still think that Microsoft is very strong ah, this framework is indeed slightly better than selenium, all things considered.
Finally I have time to update one, feel the article is useful to you, retweet and leave a comment are fine, thanks!
By the way, that upload file for why not, but also please seniors to help look ah!