diff --git a/PostmanSprint12_add-database.json b/PostmanSprint12_add-database.json new file mode 100644 index 0000000..0140080 --- /dev/null +++ b/PostmanSprint12_add-database.json @@ -0,0 +1,5181 @@ +{ + "info": { + "_postman_id": "8ed6b8f0-1e77-445f-8736-87dd5f364b51", + "name": "add-database", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "23073145", + "_collection_link": "https://universal-shadow-295426.postman.co/workspace/My-Workspace~4200f6aa-0504-44b1-8a1d-707d0dcbd5ce/collection/23073145-8ed6b8f0-1e77-445f-8736-87dd5f364b51?action=share&source=collection_link&creator=23073145" + }, + "item": [ + { + "name": "users", + "item": [ + { + "name": "User create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "const source = JSON.parse(pm.request.body.raw)\r", + "\r", + "pm.test(\"Status code is 200 or 201\", function () {\r", + " pm.expect(pm.response.code).to.be.oneOf([200,201]);\r", + "});\r", + "pm.test(\"Has user create response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "pm.test(\"Test user 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('id');\r", + "});\r", + "pm.test(\"Test user 'email' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('email');\r", + " pm.expect(jsonData.email, `\"email\" must be \"${source.mail}\"`).to.eql(source.email);\r", + "});\r", + "pm.test(\"Test user 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('name');\r", + " pm.expect(jsonData.name, `\"name\" must be \"${source.name}\"`).to.eql(source.name);\r", + "});\r", + "pm.test(\"Test user 'login' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('login');\r", + " pm.expect(jsonData.login, `\"login\" field must be \"${source.login}\"`).to.eql(source.login); \r", + "});\r", + "pm.test(\"Test user 'birthday' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('birthday');\r", + " pm.expect(jsonData.birthday, `\"birthday\" field must be \"${source.birthday}\"`).to.eql(source.birthday);\r", + "});" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user;\r", + " try {\r", + " user = rnd.getUser();\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + " pm.request.body.update({\r", + " mode: 'raw',\r", + " raw: JSON.stringify(user),\r", + " options: { raw: { language: 'json' } }\r", + " });\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"login\": \"dolore\",\n \"name\": \"Nick Name\",\n \"email\": \"mail@mail.ru\",\n \"birthday\": \"1946-08-20\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users" + ] + } + }, + "response": [] + }, + { + "name": "User create Fail login", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 400\", function () {\r", + " pm.expect(pm.response.code).to.be.equal(400);\r", + "});\r", + "pm.test(\"Has error response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"login\": \"dolore ullamco\",\n \"email\": \"yandex@mail.ru\",\n \"birthday\": \"2446-08-20\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users" + ] + } + }, + "response": [] + }, + { + "name": "User create Fail email", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 400\", function () {\r", + " pm.expect(pm.response.code).to.be.equal(400);\r", + "});\r", + "pm.test(\"Has error response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"login\": \"dolore ullamco\",\n \"name\": \"\",\n \"email\": \"mail.ru\",\n \"birthday\": \"1980-08-20\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users" + ] + } + }, + "response": [] + }, + { + "name": "User create Fail birthday", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 400\", function () {\r", + " pm.expect(pm.response.code).to.be.equal(400);\r", + "});\r", + "pm.test(\"Has error response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"login\": \"dolore\",\n \"name\": \"\",\n \"email\": \"test@mail.ru\",\n \"birthday\": \"2446-08-20\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users" + ] + } + }, + "response": [] + }, + { + "name": "User update", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "const source = pm.collectionVariables.get(\"user\")\r", + "const new_user_info = pm.collectionVariables.get(\"new_user_info\");\r", + "\r", + "pm.test(\"Status code is 200\", function () {\r", + " pm.response.to.be.ok;\r", + "});\r", + "pm.test(\"Has user update response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "pm.test(\"Test user 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('id');\r", + " pm.expect(jsonData.id, `\"id\" must be ${source.id}`).to.eql(source.id);\r", + "});\r", + "pm.test(\"Test user 'email' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('email');\r", + " pm.expect(jsonData.email, `\"email\" must be \"${new_user_info.email}\"`).to.eql(new_user_info.email);\r", + "});\r", + "pm.test(\"Test user 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('name');\r", + " pm.expect(jsonData.name, `\"name\" must be \"${new_user_info.name}\"`).to.eql(new_user_info.name);\r", + "});\r", + "pm.test(\"Test user 'login' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('login');\r", + " pm.expect(jsonData.login, `\"login\" field must be \"${new_user_info.login}\"`).to.eql(new_user_info.login); \r", + "});\r", + "pm.test(\"Test user 'birthday' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('birthday');\r", + " pm.expect(jsonData.birthday, `\"birthday\" field must be \"${new_user_info.birthday}\"`).to.eql(new_user_info.birthday);\r", + "});" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user;\r", + " try {\r", + " user = await api.addUser(rnd.getUser());\r", + " pm.collectionVariables.set(\"user\", user);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + " let new_user_info = rnd.getUser();\r", + " pm.collectionVariables.set(\"new_user_info\", new_user_info);\r", + " new_user_info[\"id\"] = user.id;\r", + "\r", + " pm.request.body.update({\r", + " mode: 'raw',\r", + " raw: JSON.stringify(new_user_info),\r", + " options: { raw: { language: 'json' } }\r", + " });\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "PUT", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users" + ] + } + }, + "response": [] + }, + { + "name": "User update unknown", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 404\", function () {\r", + " pm.expect(pm.response.code).to.be.equal(404);\r", + "});\r", + "pm.test(\"Has error response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});" + ], + "type": "text/javascript", + "packages": {} + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user;\r", + " try {\r", + " user = await api.addUser(rnd.getUser());\r", + " pm.collectionVariables.set(\"user\", user);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + " pm.request.body.update({\r", + " mode: 'raw',\r", + " raw: JSON.stringify({\r", + " \"login\": \"doloreUpdate\",\r", + " \"name\": \"est adipisicing\",\r", + " \"id\": user.id+1,\r", + " \"email\": \"mail@yandex.ru\",\r", + " \"birthday\": \"1976-09-20\"\r", + " }),\r", + " options: { raw: { language: 'json' } }\r", + " });\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "PUT", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"login\": \"doloreUpdate\",\n \"name\": \"est adipisicing\",\n \"id\": 9999,\n \"email\": \"mail@yandex.ru\",\n \"birthday\": \"1976-09-20\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users" + ] + } + }, + "response": [] + }, + { + "name": "User get All", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 200\", function () {\r", + " pm.response.to.be.ok;\r", + "});\r", + "pm.test(\"Test list user response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "pm.test(\"Test user[0] 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[0]).to.have.property('id');\r", + " pm.expect(jsonData[0].id, '\"id\" must be 1').to.eql(1);\r", + "});\r", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "*/*" + } + ], + "url": { + "raw": "{{baseUrl}}/users", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users" + ] + } + }, + "response": [] + } + ] + }, + { + "name": "friends", + "item": [ + { + "name": "Friend add", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "const user1_id = pm.collectionVariables.get(\"id\");\r", + "const user2_id = pm.collectionVariables.get(\"friend_id\");\r", + "\r", + "pm.test(\"Status code is 200\", function () {\r", + " pm.expect(pm.response.code).to.be.oneOf([200,204]);\r", + "});\r", + "\r", + "pm.sendRequest({\r", + " url : \"http://localhost:8080/users/\" + user1_id + '/friends',\r", + " method : \"GET\",\r", + " header: { \"Content-Type\": \"application/json\" }\r", + "}, (error, response) => {\r", + " pm.test(\"user1 has user2 friend\", function () {\r", + " pm.expect(response.json()[0].id).to.be.equal(user2_id);\r", + " });\r", + "});\r", + "\r", + "pm.sendRequest({\r", + " url : \"http://localhost:8080/users/\" + user2_id + '/friends',\r", + " method : \"GET\",\r", + " header: { \"Content-Type\": \"application/json\" }\r", + "}, (error, response) => {\r", + " pm.test(\"user2 doesn't have user1 friend\", function () {\r", + " pm.expect(response.json().length).to.be.equal(0);\r", + " });\r", + "});\r", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user1, user2;\r", + " try {\r", + " user1 = await api.addUser(rnd.getUser());\r", + " user2 = await api.addUser(rnd.getUser());\r", + " pm.collectionVariables.set(\"id\", user1.id);\r", + " pm.collectionVariables.set(\"friend_id\", user2.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "PUT", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users/{{id}}/friends/{{friend_id}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + "{{id}}", + "friends", + "{{friend_id}}" + ] + } + }, + "response": [] + }, + { + "name": "Friend add unknown id", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 404\", function () {\r", + " pm.expect(pm.response.code).to.be.equal(404);\r", + "});\r", + "\r", + "pm.test(\"Has error response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});" + ], + "type": "text/javascript", + "packages": {} + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user1, user2;\r", + " try {\r", + " user1 = await api.addUser(rnd.getUser());\r", + " user2 = await api.addUser(rnd.getUser());\r", + " pm.collectionVariables.set(\"id\", user1.id);\r", + " pm.collectionVariables.set(\"friend_id\", user2.id+1);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "PUT", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users/{{id}}/friends/{{friend_id}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + "{{id}}", + "friends", + "{{friend_id}}" + ] + } + }, + "response": [] + }, + { + "name": "Friend get", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "const user_friends = pm.collectionVariables.get(\"user_friends\");\r", + "\r", + "pm.test(\"Status code is 200\", function () {\r", + " pm.expect(pm.response.code).to.be.oneOf([200,204]);\r", + "});\r", + "\r", + "pm.test(\"initially user1 should have 0 friends\", function () {\r", + " pm.expect(user_friends.length).to.be.equal(0);\r", + "});\r", + "\r", + "pm.test(\"finally user1 should have 1 friend\", function () {\r", + " pm.expect(pm.response.json().length).to.be.equal(1);\r", + "});" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user1, user2, user1_friends;\r", + " try {\r", + " user1 = await api.addUser(rnd.getUser());\r", + " user2 = await api.addUser(rnd.getUser());\r", + " user1_friends = await api.getFriends(user1.id);\r", + " await api.addFriend(user1.id, user2.id);\r", + " pm.collectionVariables.set(\"id\", user1.id);\r", + " pm.collectionVariables.set(\"user_friends\", user1_friends);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + } + ], + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "method": "GET", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users/{{id}}/friends", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + "{{id}}", + "friends" + ] + } + }, + "response": [] + }, + { + "name": "Friend get unknown id", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 404\", function () {\r", + " pm.expect(pm.response.code).to.be.equal(404);\r", + "});\r", + "\r", + "pm.test(\"Has error response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});" + ], + "type": "text/javascript", + "packages": {} + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user;\r", + " try {\r", + " user = await api.addUser(rnd.getUser());\r", + " pm.collectionVariables.set(\"id\", user.id+1);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "method": "GET", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users/{{id}}/friends", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + "{{id}}", + "friends" + ] + } + }, + "response": [] + }, + { + "name": "Friend remove", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "const user1_id = pm.collectionVariables.get(\"id\");\r", + "const user2_id = pm.collectionVariables.get(\"friend_id\");\r", + "\r", + "pm.test(\"Status code is 200\", function () {\r", + " pm.expect(pm.response.code).to.be.oneOf([200,204]);\r", + "});\r", + "\r", + "pm.sendRequest({\r", + " url : \"http://localhost:8080/users/\" + user1_id + '/friends',\r", + " method : \"GET\",\r", + " header: { \"Content-Type\": \"application/json\" }\r", + "}, (error, response) => {\r", + " pm.test(\"user1 should have 0 friends\", function () {\r", + " pm.expect(response.json().length).to.be.equal(0);\r", + " });\r", + "});\r", + "\r", + "pm.sendRequest({\r", + " url : \"http://localhost:8080/users/\" + user2_id + '/friends',\r", + " method : \"GET\",\r", + " header: { \"Content-Type\": \"application/json\" }\r", + "}, (error, response) => {\r", + " pm.test(\"user2 should have 0 friends\", function () {\r", + " pm.expect(response.json().length).to.be.equal(0);\r", + " });\r", + "});\r", + "" + ], + "type": "text/javascript", + "packages": {} + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user1, user2;\r", + " try {\r", + " user1 = await api.addUser(rnd.getUser());\r", + " user2 = await api.addUser(rnd.getUser());\r", + " await api.addFriend(user1.id, user2.id);\r", + " pm.collectionVariables.set(\"id\", user1.id);\r", + " pm.collectionVariables.set(\"friend_id\", user2.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "DELETE", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users/{{id}}/friends/{{friend_id}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + "{{id}}", + "friends", + "{{friend_id}}" + ] + } + }, + "response": [] + }, + { + "name": "Not friend remove", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "const user1_id = pm.collectionVariables.get(\"id\");\r", + "const user2_id = pm.collectionVariables.get(\"friend_id\");\r", + "\r", + "pm.test(\"Status code is 200\", function () {\r", + " pm.expect(pm.response.code).to.be.oneOf([200,204]);\r", + "});\r", + "\r", + "pm.sendRequest({\r", + " url : \"http://localhost:8080/users/\" + user1_id + '/friends',\r", + " method : \"GET\",\r", + " header: { \"Content-Type\": \"application/json\" }\r", + "}, (error, response) => {\r", + " pm.test(\"user1 should have 0 friends\", function () {\r", + " pm.expect(response.json().length).to.be.equal(0);\r", + " });\r", + "});\r", + "\r", + "pm.sendRequest({\r", + " url : \"http://localhost:8080/users/\" + user2_id + '/friends',\r", + " method : \"GET\",\r", + " header: { \"Content-Type\": \"application/json\" }\r", + "}, (error, response) => {\r", + " pm.test(\"user2 should have 0 friends\", function () {\r", + " pm.expect(response.json().length).to.be.equal(0);\r", + " });\r", + "});\r", + "" + ], + "type": "text/javascript", + "packages": {} + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user1, user2;\r", + " try {\r", + " user1 = await api.addUser(rnd.getUser());\r", + " user2 = await api.addUser(rnd.getUser());\r", + " pm.collectionVariables.set(\"id\", user1.id);\r", + " pm.collectionVariables.set(\"friend_id\", user2.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "DELETE", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users/{{id}}/friends/{{friend_id}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + "{{id}}", + "friends", + "{{friend_id}}" + ] + } + }, + "response": [] + }, + { + "name": "Friend reciprocity", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "const user1_id = pm.collectionVariables.get(\"id\");\r", + "const user2_id = pm.collectionVariables.get(\"friend_id\");\r", + "\r", + "pm.test(\"Status code is 200\", function () {\r", + " pm.expect(pm.response.code).to.be.oneOf([200,204]);\r", + "});\r", + "\r", + "pm.sendRequest({\r", + " url : \"http://localhost:8080/users/\" + user1_id + '/friends',\r", + " method : \"GET\",\r", + " header: { \"Content-Type\": \"application/json\" }\r", + "}, (error, response) => {\r", + " pm.test(\"user1 should have 0 friends\", function () {\r", + " pm.expect(response.json().length).to.be.equal(0);\r", + " });\r", + "});\r", + "\r", + "pm.sendRequest({\r", + " url : \"http://localhost:8080/users/\" + user2_id + '/friends',\r", + " method : \"GET\",\r", + " header: { \"Content-Type\": \"application/json\" }\r", + "}, (error, response) => {\r", + " pm.test(\"user2 should have 1 friends\", function () {\r", + " pm.expect(response.json().length).to.be.equal(1);\r", + " });\r", + "});\r", + "" + ], + "type": "text/javascript", + "packages": {} + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user1, user2;\r", + " try {\r", + " user1 = await api.addUser(rnd.getUser());\r", + " user2 = await api.addUser(rnd.getUser());\r", + " await api.addFriend(user1.id, user2.id);\r", + " pm.collectionVariables.set(\"id\", user2.id);\r", + " pm.collectionVariables.set(\"friend_id\", user1.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "DELETE", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users/{{id}}/friends/{{friend_id}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + "{{id}}", + "friends", + "{{friend_id}}" + ] + } + }, + "response": [] + }, + { + "name": "Friend remove unknown id", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 404\", function () {\r", + " pm.expect(pm.response.code).to.be.equal(404);\r", + "});\r", + "\r", + "pm.test(\"Has error response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});" + ], + "type": "text/javascript", + "packages": {} + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user1, user2;\r", + " try {\r", + " user1 = await api.addUser(rnd.getUser());\r", + " user2 = await api.addUser(rnd.getUser());\r", + " await api.addFriend(user1.id, user2.id);\r", + " pm.collectionVariables.set(\"id\", user1.id + 4);\r", + " pm.collectionVariables.set(\"friend_id\", user2.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "DELETE", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users/{{id}}/friends/{{friend_id}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + "{{id}}", + "friends", + "{{friend_id}}" + ] + } + }, + "response": [] + }, + { + "name": "Friend remove unknown friend id", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 404\", function () {\r", + " pm.expect(pm.response.code).to.be.equal(404);\r", + "});\r", + "\r", + "pm.test(\"Has error response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});" + ], + "type": "text/javascript", + "packages": {} + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user1, user2;\r", + " try {\r", + " user1 = await api.addUser(rnd.getUser());\r", + " user2 = await api.addUser(rnd.getUser());\r", + " await api.addFriend(user1.id, user2.id);\r", + " pm.collectionVariables.set(\"id\", user1.id);\r", + " pm.collectionVariables.set(\"friend_id\", user2.id+1);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "DELETE", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users/{{id}}/friends/{{friend_id}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + "{{id}}", + "friends", + "{{friend_id}}" + ] + } + }, + "response": [] + }, + { + "name": "Get common friends", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "const user3_id = pm.collectionVariables.get(\"user3_id\");\r", + "\r", + "pm.test(\"Status code is 200\", function () {\r", + " pm.expect(pm.response.code).to.be.oneOf([200,204]);\r", + "});\r", + "\r", + "pm.test(\"user1 should have 1 common friend with user2\", function () {\r", + " pm.expect(pm.response.json().length).to.be.equal(1);\r", + " pm.expect(pm.response.json()[0].id).to.be.equal(user3_id);\r", + "});\r", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user1, user2, user3;\r", + " try {\r", + " user1 = await api.addUser(rnd.getUser());\r", + " user2 = await api.addUser(rnd.getUser());\r", + " user3 = await api.addUser(rnd.getUser());\r", + " await api.addFriend(user1.id, user3.id);\r", + " await api.addFriend(user1.id, user2.id);\r", + " await api.addFriend(user2.id, user3.id);\r", + " pm.collectionVariables.set(\"id\", user1.id);\r", + " pm.collectionVariables.set(\"friend_id\", user2.id);\r", + " pm.collectionVariables.set(\"user3_id\", user3.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + } + ], + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "method": "GET", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users/{{id}}/friends/common/{{friend_id}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + "{{id}}", + "friends", + "common", + "{{friend_id}}" + ] + } + }, + "response": [] + } + ] + }, + { + "name": "films", + "item": [ + { + "name": "Film create", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "const source = JSON.parse(pm.request.body.raw)\r", + "\r", + "pm.test(\"Status code is 200 or 201\", function () {\r", + " pm.expect(pm.response.code).to.be.oneOf([200,201]);\r", + "});\r", + "pm.test(\"Has film create response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "pm.test(\"Test film 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('id');\r", + "});\r", + "pm.test(\"Test film 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('name');\r", + " pm.expect(jsonData.name, `\"name\" must be \"${source.name}\"`).to.eql(source.name);\r", + "});\r", + "pm.test(\"Test film 'description' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('description');\r", + " pm.expect(jsonData.description, `\"description\" must be \"${source.description}\"`).to.eql(source.description);\r", + "});\r", + "pm.test(\"Test film 'releaseDate' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('releaseDate');\r", + " pm.expect(jsonData.releaseDate, `\"releaseDate\" field must be \"${source.releaseDate}\"`).to.eql(source.releaseDate);\r", + "});\r", + "pm.test(\"Test film 'duration' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('duration');\r", + " pm.expect(jsonData.duration, `\"duration\" field must be %{source.duration}`).to.eql(source.duration); \r", + "});\r", + "pm.test(\"Test film 'mpa' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('mpa');\r", + " pm.expect(jsonData.mpa.id, `\"mpa.id\" field must be %{source.mpa.id}`).to.eql(source.mpa.id); \r", + "});\r", + "pm.test(\"Test film 'genres' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " let responseGenres = [];\r", + " let requestGenres = [];\r", + " source.genres.forEach((element) => requestGenres.push(element.id));\r", + " jsonData.genres.forEach((element) => responseGenres.push(element.id));\r", + " pm.expect(jsonData).to.have.property('genres');\r", + " pm.expect(responseGenres, `\"genres\" field must be %{requestGenres}`).to.eql(requestGenres); \r", + "});\r", + "\r", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let film;\r", + " try {\r", + " film = rnd.getFilm();\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + " pm.request.body.update({\r", + " mode: 'raw',\r", + " raw: JSON.stringify(film),\r", + " options: { raw: { language: 'json' } }\r", + " });\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"name\": \"nisi eiusmod\",\n \"description\": \"adipisicing\",\n \"releaseDate\": \"1967-03-25\",\n \"duration\": 100\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/films", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films" + ] + } + }, + "response": [] + }, + { + "name": "Film create several genres", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "const source = JSON.parse(pm.request.body.raw)\r", + "\r", + "pm.test(\"Status code is 200 or 201\", function () {\r", + " pm.expect(pm.response.code).to.be.oneOf([200,201]);\r", + "});\r", + "pm.test(\"Has film create response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "pm.test(\"Test film 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('id');\r", + "});\r", + "pm.test(\"Test film 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('name');\r", + " pm.expect(jsonData.name, `\"name\" must be \"${source.name}\"`).to.eql(source.name);\r", + "});\r", + "pm.test(\"Test film 'description' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('description');\r", + " pm.expect(jsonData.description, `\"description\" must be \"${source.description}\"`).to.eql(source.description);\r", + "});\r", + "pm.test(\"Test film 'releaseDate' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('releaseDate');\r", + " pm.expect(jsonData.releaseDate, `\"releaseDate\" field must be \"${source.releaseDate}\"`).to.eql(source.releaseDate);\r", + "});\r", + "pm.test(\"Test film 'duration' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('duration');\r", + " pm.expect(jsonData.duration, `\"duration\" field must be %{source.duration}`).to.eql(source.duration); \r", + "});\r", + "pm.test(\"Test film 'mpa' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('mpa');\r", + " pm.expect(jsonData.mpa.id, `\"mpa.id\" field must be %{source.mpa.id}`).to.eql(source.mpa.id); \r", + "});\r", + "pm.test(\"Test film 'genres' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " let responseGenres = [];\r", + " let requestGenres = [];\r", + " source.genres.forEach((element) => requestGenres.push(element.id));\r", + " jsonData.genres.forEach((element) => responseGenres.push(element.id));\r", + " pm.expect(jsonData).to.have.property('genres');\r", + " pm.expect(responseGenres, `\"genres\" field must be %{requestGenres}`).to.eql(requestGenres); \r", + "});\r", + "\r", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let film;\r", + " try {\r", + " film = rnd.getFilm();\r", + " film.genres = [\r", + " {\"id\": 3},\r", + " {\"id\": 5}\r", + " ]\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + " pm.request.body.update({\r", + " mode: 'raw',\r", + " raw: JSON.stringify(film),\r", + " options: { raw: { language: 'json' } }\r", + " });\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"name\": \"nisi eiusmod\",\n \"description\": \"adipisicing\",\n \"releaseDate\": \"1967-03-25\",\n \"duration\": 100\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/films", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films" + ] + } + }, + "response": [] + }, + { + "name": "Film create Fail name", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 400\", function () {\r", + " pm.expect(pm.response.code).to.be.equal(400);\r", + "});\r", + "pm.test(\"Has error response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"name\": \"\",\n \"description\": \"Description\",\n \"releaseDate\": \"1900-03-25\",\n \"duration\": 200,\n \"mpa\": { \"id\": 1}\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/films", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films" + ] + } + }, + "response": [] + }, + { + "name": "Film create Fail description", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 400\", function () {\r", + " pm.expect(pm.response.code).to.be.equal(400);\r", + "});\r", + "pm.test(\"Has error response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"name\": \"Film name\",\n \"description\": \"Пятеро друзей ( комик-группа «Шарло»), приезжают в город Бризуль. Здесь они хотят разыскать господина Огюста Куглова, который задолжал им деньги, а именно 20 миллионов. о Куглов, который за время «своего отсутствия», стал кандидатом Коломбани.\",\n \"releaseDate\": \"1900-03-25\",\n \"duration\": 200,\n \"mpa\": { \"id\": 1}\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/films", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films" + ] + } + }, + "response": [] + }, + { + "name": "Film create Fail releaseDate", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 400\", function () {\r", + " pm.expect(pm.response.code).to.be.equal(400);\r", + "});\r", + "pm.test(\"Has error response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"name\": \"Name\",\n \"description\": \"Description\",\n \"releaseDate\": \"1890-03-25\",\n \"duration\": 200,\n \"mpa\": { \"id\": 1}\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/films", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films" + ] + } + }, + "response": [] + }, + { + "name": "Film create Fail duration", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 400\", function () {\r", + " pm.expect(pm.response.code).to.be.equal(400);\r", + "});\r", + "pm.test(\"Has error response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"name\": \"Name\",\n \"description\": \"Descrition\",\n \"releaseDate\": \"1980-03-25\",\n \"duration\": -200,\n \"mpa\": { \"id\": 1}\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/films", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films" + ] + } + }, + "response": [] + }, + { + "name": "Film create Fail MPA", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 404\", function () {\r", + " pm.expect(pm.response.code).to.be.equal(404);\r", + "});\r", + "pm.test(\"Has error response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"name\": \"Name\",\n \"description\": \"Descrition\",\n \"releaseDate\": \"1980-03-25\",\n \"duration\": 200,\n \"mpa\": { \"id\": 10}\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/films", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films" + ] + } + }, + "response": [] + }, + { + "name": "Film create Fail Genre", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 404\", function () {\r", + " pm.expect(pm.response.code).to.be.equal(404);\r", + "});\r", + "pm.test(\"Has error response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"name\": \"Name\",\n \"description\": \"Descrition\",\n \"releaseDate\": \"1980-03-25\",\n \"duration\": 200,\n \"mpa\": { \"id\": 5},\n \"genres\": [\n {\"id\": 500}\n ]\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/films", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films" + ] + } + }, + "response": [] + }, + { + "name": "Film update", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "const source = pm.collectionVariables.get(\"film\")\r", + "\r", + "pm.test(\"Status code is 200\", function () {\r", + " pm.response.to.be.ok;\r", + "});\r", + "pm.test(\"Has film update response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "\r", + "pm.test(\"Test film 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('id');\r", + " pm.expect(jsonData.id, `\"id\" must be ${source.id}`).to.eql(source.id);\r", + "});\r", + "pm.test(\"Test film 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('name');\r", + " pm.expect(jsonData.name, '\"name\" must be \"Film Updated\"').to.eql('Film Updated');\r", + "});\r", + "pm.test(\"Test film 'description' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('description');\r", + " pm.expect(jsonData.description, '\"description\" must be \"New film update decription\"').to.eql('New film update decription');\r", + "});\r", + "pm.test(\"Test film 'releaseDate' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('releaseDate');\r", + " pm.expect(jsonData.releaseDate, '\"releaseDate\" field must be \"1989-04-17\"').to.eql('1989-04-17');\r", + "});\r", + "pm.test(\"Test film 'duration' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('duration');\r", + " pm.expect(jsonData.duration, '\"duration\" field must be 190').to.eql(190); \r", + "});\r", + "\r", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user;\r", + " try {\r", + " film = await api.addFilm(rnd.getFilm());\r", + " pm.collectionVariables.set(\"film\", film);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + " pm.request.body.update({\r", + " mode: 'raw',\r", + " raw: JSON.stringify({\r", + " \"id\": film.id,\r", + " \"name\": \"Film Updated\",\r", + " \"releaseDate\": \"1989-04-17\",\r", + " \"description\": \"New film update decription\",\r", + " \"duration\": 190,\r", + " \"rate\": 4,\r", + " \"mpa\": { \"id\": 3}\r", + " }),\r", + " options: { raw: { language: 'json' } }\r", + " });\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "PUT", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/films", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films" + ] + } + }, + "response": [] + }, + { + "name": "Film update unknown", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 500\", function () {\r", + " pm.expect(pm.response.code).to.be.oneOf([500, 404]);\r", + "});\r", + "pm.test(\"Has error response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user;\r", + " try {\r", + " film = await api.addFilm(rnd.getFilm());\r", + " pm.collectionVariables.set(\"film\", film);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + " pm.request.body.update({\r", + " mode: 'raw',\r", + " raw: JSON.stringify({\r", + " \"id\": film.id+1,\r", + " \"name\": \"Film Updated\",\r", + " \"releaseDate\": \"1989-04-17\",\r", + " \"description\": \"New film update decription\",\r", + " \"duration\": 190,\r", + " \"rate\": 4,\r", + " \"mpa\": { \"id\": 3}\r", + " }),\r", + " options: { raw: { language: 'json' } }\r", + " });\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "PUT", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/films", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films" + ] + } + }, + "response": [] + }, + { + "name": "Film get All", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 200\", function () {\r", + " pm.response.to.be.ok;\r", + "});\r", + "pm.test(\"Test list film response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "pm.test(\"Test film[0] 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[0]).to.have.property('id');\r", + " pm.expect(jsonData[0].id, '\"id\" must be 1').to.eql(1);\r", + "});\r", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "*/*" + } + ], + "url": { + "raw": "{{baseUrl}}/films", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films" + ] + } + }, + "response": [] + }, + { + "name": "Film get Popular", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "const film1_id = pm.collectionVariables.get(\"film1_id\");\r", + "const film2_id = pm.collectionVariables.get(\"film2_id\");\r", + "const film3_id = pm.collectionVariables.get(\"film3_id\");\r", + "\r", + "pm.test(\"Status code is 200\", function () {\r", + " pm.response.to.be.ok;\r", + "});\r", + "pm.test(\"Test list popular film response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "\r", + "const index1 = pm.response.json().findIndex(x => x.id == film1_id);\r", + "const index2 = pm.response.json().findIndex(x => x.id == film2_id);\r", + "const index3 = pm.response.json().findIndex(x => x.id == film3_id);\r", + "\r", + "pm.test(\"Test films сonsistency\", function () {\r", + " pm.expect(index1).to.be.above(index2);\r", + " pm.expect(index1).to.be.above(index3);\r", + " pm.expect(index3).to.be.above(index2);\r", + "});\r", + "\r", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user1, user2, user3, film1, film2, film3;\r", + " try {\r", + " user1 = await api.addUser(rnd.getUser());\r", + " user2 = await api.addUser(rnd.getUser());\r", + " user3 = await api.addUser(rnd.getUser());\r", + " film1 = await api.addFilm(rnd.getFilm());\r", + " film2 = await api.addFilm(rnd.getFilm());\r", + " film3 = await api.addFilm(rnd.getFilm());\r", + " await api.addLike(film2.id, user1.id);\r", + " await api.addLike(film2.id, user2.id);\r", + " await api.addLike(film2.id, user3.id);\r", + " await api.addLike(film3.id, user1.id);\r", + " await api.addLike(film3.id, user2.id);\r", + " await api.addLike(film1.id, user1.id);\r", + " pm.collectionVariables.set(\"film1_id\", film1.id);\r", + " pm.collectionVariables.set(\"film2_id\", film2.id);\r", + " pm.collectionVariables.set(\"film3_id\", film3.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "*/*" + } + ], + "url": { + "raw": "{{baseUrl}}/films/popular?count=1000", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + "popular" + ], + "query": [ + { + "key": "count", + "value": "1000" + } + ] + } + }, + "response": [] + } + ] + }, + { + "name": "like", + "item": [ + { + "name": "Add like", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 200\", function () {\r", + " pm.expect(pm.response.code).to.be.oneOf([200,204]);\r", + "});\r", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user, film;\r", + " try {\r", + " user = await api.addUser(rnd.getUser());\r", + " film = await api.addFilm(rnd.getFilm());\r", + " pm.collectionVariables.set(\"id\", user.id);\r", + " pm.collectionVariables.set(\"film_id\", film.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "PUT", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/films/{{film_id}}/like/{{id}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + "{{film_id}}", + "like", + "{{id}}" + ] + } + }, + "response": [] + }, + { + "name": "Remove like", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 200\", function () {\r", + " pm.expect(pm.response.code).to.be.oneOf([200,204]);\r", + "});\r", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " let user, film;\r", + " try {\r", + " user = await api.addUser(rnd.getUser());\r", + " film = await api.addFilm(rnd.getFilm());\r", + " await api.addLike(film.id, user.id);\r", + " pm.collectionVariables.set(\"id\", user.id);\r", + " pm.collectionVariables.set(\"film_id\", film.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "DELETE", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + }, + { + "key": "Accept", + "value": "*/*" + } + ], + "body": { + "mode": "raw", + "raw": "", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/films/{{film_id}}/like/{{id}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + "{{film_id}}", + "like", + "{{id}}" + ] + } + }, + "response": [] + } + ] + }, + { + "name": "MPA", + "item": [ + { + "name": "Get MPA name by id", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 200\", function () {\r", + " pm.response.to.be.ok;\r", + "});\r", + "pm.test(\"Get MPA response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "\r", + "const source = pm.collectionVariables.get(\"source\");\r", + "\r", + "pm.test(\"Test MPA 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('id');\r", + " pm.expect(jsonData.id, `\"id\" must be ${source}`).to.eql(source);\r", + "});\r", + "\r", + "const MPAS = {\r", + " 1: \"G\",\r", + " 2: \"PG\",\r", + " 3: \"PG-13\",\r", + " 4: \"R\",\r", + " 5: \"NC-17\"\r", + "}\r", + "\r", + "pm.test(\"Test MPA 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('name');\r", + " pm.expect(jsonData.name, `\"name\" must be \"${MPAS[source]}\"`).to.eql(MPAS[source]);\r", + "});\r", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const mpa = Math.floor(Math.random() * (5 - 1 + 1) + 1);\r", + "pm.collectionVariables.set(\"id\", mpa);\r", + "pm.collectionVariables.set(\"source\", mpa)" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "*/*" + } + ], + "url": { + "raw": "{{baseUrl}}/mpa/{{id}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "mpa", + "{{id}}" + ] + } + }, + "response": [ + { + "name": "OK", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Not Found", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Not Found", + "code": 404, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Conflict", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Conflict", + "code": 409, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Internal Server Error", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Internal Server Error", + "code": 500, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + } + ] + }, + { + "name": "MPA id=9999 get not found", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 404\", function () {\r", + " pm.response.to.have.status(404);\r", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "*/*" + } + ], + "url": { + "raw": "{{baseUrl}}/mpa/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "mpa", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "9999", + "description": "(Required) " + } + ] + } + }, + "response": [ + { + "name": "OK", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Not Found", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Not Found", + "code": 404, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Conflict", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Conflict", + "code": 409, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Internal Server Error", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Internal Server Error", + "code": 500, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + } + ] + }, + { + "name": "MPA get All", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 200\", function () {\r", + " pm.response.to.be.ok;\r", + "});\r", + "pm.test(\"Test list MPA response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData.length, 'List length must be 5').to.eql(5);\r", + "});\r", + "pm.test(\"Test MPA[0] 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[0]).to.have.property('id');\r", + " pm.expect(jsonData[0].id, '\"id\" must be 1').to.eql(1);\r", + "});\r", + "pm.test(\"Test MPA[0] 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[0]).to.have.property('name');\r", + " pm.expect(jsonData[0].name, '\"name\" must be \"G\"').to.eql('G');\r", + "});\r", + "pm.test(\"Test MPA[1] 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[1]).to.have.property('id');\r", + " pm.expect(jsonData[1].id, '\"id\" must be 2').to.eql(2);\r", + "});\r", + "pm.test(\"Test MPA[1] 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[1]).to.have.property('name');\r", + " pm.expect(jsonData[1].name, '\"name\" must be \"PG\"').to.eql('PG');\r", + "});\r", + "pm.test(\"Test MPA[2] 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[2]).to.have.property('id');\r", + " pm.expect(jsonData[2].id, '\"id\" must be 3').to.eql(3);\r", + "});\r", + "pm.test(\"Test MPA[2] 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[2]).to.have.property('name');\r", + " pm.expect(jsonData[2].name, '\"name\" must be \"PG-13\"').to.eql('PG-13');\r", + "});\r", + "pm.test(\"Test MPA[3] 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[3]).to.have.property('id');\r", + " pm.expect(jsonData[3].id, '\"id\" must be 4').to.eql(4);\r", + "});\r", + "pm.test(\"Test MPA[3] 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[3]).to.have.property('name');\r", + " pm.expect(jsonData[3].name, '\"name\" must be \"R\"').to.eql('R');\r", + "});\r", + "pm.test(\"Test MPA[4] 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[4]).to.have.property('id');\r", + " pm.expect(jsonData[4].id, '\"id\" must be 5').to.eql(5);\r", + "});\r", + "pm.test(\"Test MPA[4] 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[4]).to.have.property('name');\r", + " pm.expect(jsonData[4].name, '\"name\" must be \"NC-17\"').to.eql('NC-17');\r", + "});\r", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "*/*" + } + ], + "url": { + "raw": "{{baseUrl}}/mpa", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "mpa" + ] + } + }, + "response": [ + { + "name": "OK", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users" + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + } + ] + } + ] + }, + { + "name": "Genre", + "item": [ + { + "name": "Get Genre name by id", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 200\", function () {\r", + " pm.response.to.be.ok;\r", + "});\r", + "pm.test(\"Get MPA response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "\r", + "const source = pm.collectionVariables.get(\"source\");\r", + "\r", + "pm.test(\"Test MPA 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('id');\r", + " pm.expect(jsonData.id, `\"id\" must be ${source}`).to.eql(source);\r", + "});\r", + "\r", + "const MPAS = {\r", + " 1: \"Комедия\",\r", + " 2: \"Драма\",\r", + " 3: \"Мультфильм\",\r", + " 4: \"Триллер\",\r", + " 5: \"Документальный\",\r", + " 6: \"Боевик\"\r", + "}\r", + "\r", + "pm.test(\"Test MPA 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('name');\r", + " pm.expect(jsonData.name, `\"name\" must be \"${MPAS[source]}\"`).to.eql(MPAS[source]);\r", + "});\r", + "" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const mpa = Math.floor(Math.random() * (6 - 1 + 1) + 1);\r", + "pm.collectionVariables.set(\"id\", mpa);\r", + "pm.collectionVariables.set(\"source\", mpa)" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "*/*" + } + ], + "url": { + "raw": "{{baseUrl}}/genres/{{id}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "genres", + "{{id}}" + ] + } + }, + "response": [ + { + "name": "OK", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Not Found", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Not Found", + "code": 404, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Conflict", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Conflict", + "code": 409, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Internal Server Error", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Internal Server Error", + "code": 500, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + } + ] + }, + { + "name": "Genre id=9999 get not found", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 404\", function () {\r", + " pm.response.to.have.status(404);\r", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "*/*" + } + ], + "url": { + "raw": "{{baseUrl}}/genres/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "genres", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "9999", + "description": "(Required) " + } + ] + } + }, + "response": [ + { + "name": "OK", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Not Found", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Not Found", + "code": 404, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Conflict", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Conflict", + "code": 409, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Internal Server Error", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Internal Server Error", + "code": 500, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + } + ] + }, + { + "name": "Genre get All", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 200\", function () {\r", + " pm.response.to.be.ok;\r", + "});\r", + "pm.test(\"Test list genre response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData.length, 'List length must be 6').to.eql(6);\r", + "});\r", + "pm.test(\"Test genre[0] 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[0]).to.have.property('id');\r", + " pm.expect(jsonData[0].id, '\"id\" must be 1').to.eql(1);\r", + "});\r", + "pm.test(\"Test genre[0] 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[0]).to.have.property('name');\r", + " pm.expect(jsonData[0].name, '\"name\" must be \"Комедия\"').to.eql('Комедия');\r", + "});\r", + "pm.test(\"Test genre[1] 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[1]).to.have.property('id');\r", + " pm.expect(jsonData[1].id, '\"id\" must be 2').to.eql(2);\r", + "});\r", + "pm.test(\"Test genre[1] 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[1]).to.have.property('name');\r", + " pm.expect(jsonData[1].name, '\"name\" must be \"Драма\"').to.eql('Драма');\r", + "});\r", + "pm.test(\"Test genre[2] 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[2]).to.have.property('id');\r", + " pm.expect(jsonData[2].id, '\"id\" must be 3').to.eql(3);\r", + "});\r", + "pm.test(\"Test genre[2] 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[2]).to.have.property('name');\r", + " pm.expect(jsonData[2].name, '\"name\" must be \"Мультфильм\"').to.eql('Мультфильм');\r", + "});\r", + "pm.test(\"Test genre[3] 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[3]).to.have.property('id');\r", + " pm.expect(jsonData[3].id, '\"id\" must be 4').to.eql(4);\r", + "});\r", + "pm.test(\"Test genre[3] 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[3]).to.have.property('name');\r", + " pm.expect(jsonData[3].name, '\"name\" must be \"Триллер\"').to.eql('Триллер');\r", + "});\r", + "pm.test(\"Test genre[4] 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[4]).to.have.property('id');\r", + " pm.expect(jsonData[4].id, '\"id\" must be 5').to.eql(5);\r", + "});\r", + "pm.test(\"Test genre[4] 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[4]).to.have.property('name');\r", + " pm.expect(jsonData[4].name, '\"name\" must be \"Документальный\"').to.eql('Документальный');\r", + "});\r", + "pm.test(\"Test genre[5] 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[5]).to.have.property('id');\r", + " pm.expect(jsonData[5].id, '\"id\" must be 6').to.eql(6);\r", + "});\r", + "pm.test(\"Test genre[5] 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData[5]).to.have.property('name');\r", + " pm.expect(jsonData[5].name, '\"name\" must be \"Боевик\"').to.eql('Боевик');\r", + "});\r", + "\r", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "*/*" + } + ], + "url": { + "raw": "{{baseUrl}}/genres", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "genres" + ] + } + }, + "response": [ + { + "name": "OK", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users" + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + } + ] + }, + { + "name": "Film get with genre", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 200\", function () {\r", + " pm.response.to.be.ok;\r", + "});\r", + "pm.test(\"Get film response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "pm.test(\"Test film 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('id');\r", + " var filmId = pm.collectionVariables.get(\"id\");\r", + " pm.expect(jsonData.id, `\"id\" must be ${filmId}`).to.eql(filmId);\r", + "});\r", + "pm.test(\"Test film 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('name');\r", + " pm.expect(jsonData.name, '\"name\" must be \"Film Updated\"').to.eql('Film Updated');\r", + "});\r", + "pm.test(\"Test film 'description' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('description');\r", + " pm.expect(jsonData.description, '\"description\" must be \"New film update decription\"').to.eql('New film update decription');\r", + "});\r", + "pm.test(\"Test film 'releaseDate' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('releaseDate');\r", + " pm.expect(jsonData.releaseDate, '\"releaseDate\" field must be \"1989-04-17\"').to.eql('1989-04-17');\r", + "});\r", + "pm.test(\"Test film 'duration' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('duration');\r", + " pm.expect(jsonData.duration, '\"duration\" field must be 190').to.eql(190); \r", + "});\r", + "pm.test(\"Test film 'mpa' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('mpa');\r", + " pm.expect(jsonData.mpa).to.have.property('id');\r", + " pm.expect(jsonData.mpa.id, '\"mpa.id\" field must be 5').to.eql(5); \r", + " pm.expect(jsonData.mpa).to.have.property('name');\r", + " pm.expect(jsonData.mpa.name, '\"mpa.name\" field must be \"PG\"').to.eql(\"NC-17\"); \r", + "});\r", + "\r", + "pm.test(\"Test film 'genres' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('genres');\r", + " pm.expect(jsonData.genres.length, '\"genres\" field must be have 1 genre').to.eql(1);\r", + " pm.expect(jsonData.genres[0]).to.have.property('id');\r", + " pm.expect(jsonData.genres[0].id, '\"genres[0].id\" field must be 2').to.eql(2); \r", + " pm.expect(jsonData.genres[0]).to.have.property('name');\r", + " pm.expect(jsonData.genres[0].name, '\"genres[0].name\" field must be \"Драма\"').to.eql('Драма');\r", + "});\r", + "" + ], + "type": "text/javascript", + "packages": {} + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " try {\r", + " film = await api.addFilm({\r", + " \"name\": \"Film Updated\",\r", + " \"releaseDate\": \"1989-04-17\",\r", + " \"description\": \"New film update decription\",\r", + " \"duration\": 190,\r", + " \"rate\": 4,\r", + " \"mpa\": { \"id\": 5},\r", + " \"genres\": [{ \"id\": 2}]\r", + " });\r", + " pm.collectionVariables.set(\"id\", film.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "*/*" + } + ], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{id}}", + "description": "(Required) " + } + ] + } + }, + "response": [ + { + "name": "OK", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Not Found", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Not Found", + "code": 404, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Conflict", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Conflict", + "code": 409, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Internal Server Error", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Internal Server Error", + "code": 500, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + } + ] + }, + { + "name": "Film get without genre", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 200\", function () {\r", + " pm.response.to.be.ok;\r", + "});\r", + "pm.test(\"Get film response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "pm.test(\"Test film 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('id');\r", + " var filmId = pm.collectionVariables.get(\"id\");\r", + " pm.expect(jsonData.id, `\"id\" must be ${filmId}`).to.eql(filmId);\r", + "});\r", + "pm.test(\"Test film 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('name');\r", + " pm.expect(jsonData.name, '\"name\" must be \"New film\"').to.eql('New film');\r", + "});\r", + "pm.test(\"Test film 'description' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('description');\r", + " pm.expect(jsonData.description, '\"description\" must be \"New film about friends\"').to.eql('New film about friends');\r", + "});\r", + "pm.test(\"Test film 'releaseDate' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('releaseDate');\r", + " pm.expect(jsonData.releaseDate, '\"releaseDate\" field must be \"1999-04-30\"').to.eql('1999-04-30');\r", + "});\r", + "pm.test(\"Test film 'duration' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('duration');\r", + " pm.expect(jsonData.duration, '\"duration\" field must be 120').to.eql(120); \r", + "});\r", + "pm.test(\"Test film 'mpa' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('mpa');\r", + " pm.expect(jsonData.mpa).to.have.property('id');\r", + " pm.expect(jsonData.mpa.id, '\"mpa.id\" field must be 3').to.eql(3); \r", + " pm.expect(jsonData.mpa).to.have.property('name');\r", + " pm.expect(jsonData.mpa.name, '\"mpa.name\" field must be \"PG-13\"').to.eql(\"PG-13\"); \r", + "});\r", + "\r", + "pm.test(\"Test film 'genres' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('genres');\r", + " if (jsonData.genres != null) {\r", + " pm.expect(jsonData.genres.length, '\"genres\" field must be have 0 genre').to.eql(0);\r", + " }\r", + "});\r", + "" + ], + "type": "text/javascript", + "packages": {} + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " try {\r", + " film = await api.addFilm({\r", + " \"name\": \"New film\",\r", + " \"releaseDate\": \"1999-04-30\",\r", + " \"description\": \"New film about friends\",\r", + " \"duration\": 120,\r", + " \"mpa\": { \"id\": 3}\r", + " });\r", + " pm.collectionVariables.set(\"id\", film.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "*/*" + } + ], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{id}}", + "description": "(Required) " + } + ] + } + }, + "response": [ + { + "name": "OK", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Not Found", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Not Found", + "code": 404, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Conflict", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Conflict", + "code": 409, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Internal Server Error", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Internal Server Error", + "code": 500, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + } + ] + }, + { + "name": "Film get with genres", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 200\", function () {\r", + " pm.response.to.be.ok;\r", + "});\r", + "pm.test(\"Get film response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "pm.test(\"Test film 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('id');\r", + " var filmId = pm.collectionVariables.get(\"id\");\r", + " pm.expect(jsonData.id, `\"id\" must be ${filmId}`).to.eql(filmId);\r", + "});\r", + "pm.test(\"Test film 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('name');\r", + " pm.expect(jsonData.name, '\"name\" must be \"New film\"').to.eql('New film');\r", + "});\r", + "pm.test(\"Test film 'description' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('description');\r", + " pm.expect(jsonData.description, '\"description\" must be \"New film about friends\"').to.eql('New film about friends');\r", + "});\r", + "pm.test(\"Test film 'releaseDate' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('releaseDate');\r", + " pm.expect(jsonData.releaseDate, '\"releaseDate\" field must be \"1999-04-30\"').to.eql('1999-04-30');\r", + "});\r", + "pm.test(\"Test film 'duration' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('duration');\r", + " pm.expect(jsonData.duration, '\"duration\" field must be 100').to.eql(120); \r", + "});\r", + "\r", + "pm.test(\"Test film 'mpa.id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('mpa');\r", + " pm.expect(jsonData.mpa).to.have.property('id');\r", + " pm.expect(jsonData.mpa.id, '\"mpa.id\" field must be 3').to.eql(3);\r", + " pm.expect(jsonData.mpa).to.have.property('name');\r", + " pm.expect(jsonData.mpa.name, '\"mpa.name\" field must be \"PG-13\"').to.eql(\"PG-13\");\r", + "});\r", + "\r", + "pm.test(\"Test film 'genres' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('genres');\r", + " pm.expect(jsonData.genres.length, '\"genres\" field must be have 3 genres').to.eql(3);\r", + " pm.expect(jsonData.genres[0]).to.have.property('id');\r", + " pm.expect(jsonData.genres[0].id, '\"genres[0].id\" field must be 1').to.eql(1); \r", + " pm.expect(jsonData.genres[0]).to.have.property('name');\r", + " pm.expect(jsonData.genres[0].name, '\"genres[0].name\" field must be \"Комедия\"').to.eql('Комедия');\r", + " pm.expect(jsonData.genres[1]).to.have.property('id');\r", + " pm.expect(jsonData.genres[1].id, '\"genres[1].id\" field must be 2').to.eql(2);\r", + " pm.expect(jsonData.genres[1]).to.have.property('name');\r", + " pm.expect(jsonData.genres[1].name, '\"genres[1].name\" field must be \"Драма\"').to.eql('Драма');\r", + " pm.expect(jsonData.genres[2]).to.have.property('id');\r", + " pm.expect(jsonData.genres[2].id, '\"genres[2].id\" field must be 3').to.eql(3);\r", + " pm.expect(jsonData.genres[2]).to.have.property('name');\r", + " pm.expect(jsonData.genres[2].name, '\"genres[2].name\" field must be \"Мультфильм\"').to.eql('Мультфильм');\r", + "});" + ], + "type": "text/javascript", + "packages": {} + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " try {\r", + " film = await api.addFilm({\r", + " \"name\": \"New film\",\r", + " \"releaseDate\": \"1999-04-30\",\r", + " \"description\": \"New film about friends\",\r", + " \"duration\": 120,\r", + " \"mpa\": { \"id\": 3},\r", + " \"genres\": [{ \"id\": 1}, { \"id\": 2}, { \"id\": 3}]\r", + " });\r", + " pm.collectionVariables.set(\"id\", film.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "*/*" + } + ], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{id}}", + "description": "(Required) " + } + ] + } + }, + "response": [ + { + "name": "OK", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Not Found", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Not Found", + "code": 404, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Conflict", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Conflict", + "code": 409, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Internal Server Error", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Internal Server Error", + "code": 500, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + } + ] + }, + { + "name": "Film get with genre without duplicate", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Status code is 200\", function () {\r", + " pm.response.to.be.ok;\r", + "});\r", + "pm.test(\"Get film response\", function () {\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "pm.test(\"Test film 'id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('id');\r", + " var filmId = pm.collectionVariables.get(\"id\");\r", + " pm.expect(jsonData.id, `\"id\" must be ${filmId}`).to.eql(filmId);\r", + "});\r", + "pm.test(\"Test film 'name' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('name');\r", + " pm.expect(jsonData.name, '\"name\" must be \"New film\"').to.eql('New film');\r", + "});\r", + "pm.test(\"Test film 'description' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('description');\r", + " pm.expect(jsonData.description, '\"description\" must be \"New film about friends\"').to.eql('New film about friends');\r", + "});\r", + "pm.test(\"Test film 'releaseDate' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('releaseDate');\r", + " pm.expect(jsonData.releaseDate, '\"releaseDate\" field must be \"1999-04-30\"').to.eql('1999-04-30');\r", + "});\r", + "pm.test(\"Test film 'duration' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('duration');\r", + " pm.expect(jsonData.duration, '\"duration\" field must be 100').to.eql(120); \r", + "});\r", + "\r", + "pm.test(\"Test film 'mpa.id' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('mpa');\r", + " pm.expect(jsonData.mpa).to.have.property('id');\r", + " pm.expect(jsonData.mpa.id, '\"mpa.id\" field must be 3').to.eql(3);\r", + " pm.expect(jsonData.mpa).to.have.property('name');\r", + " pm.expect(jsonData.mpa.name, '\"mpa.name\" field must be \"PG-13\"').to.eql(\"PG-13\");\r", + "});\r", + "\r", + "pm.test(\"Test film 'genres' field\", function () {\r", + " var jsonData = pm.response.json();\r", + " pm.expect(jsonData).to.have.property('genres');\r", + " pm.expect(jsonData.genres.length, '\"genres\" field must be have 2 genres').to.eql(2);\r", + " pm.expect(jsonData.genres[0]).to.have.property('id');\r", + " pm.expect(jsonData.genres[0].id, '\"genres[0].id\" field must be 1').to.eql(1); \r", + " pm.expect(jsonData.genres[0]).to.have.property('name');\r", + " pm.expect(jsonData.genres[0].name, '\"genres[0].name\" field must be \"Комедия\"').to.eql('Комедия');\r", + " pm.expect(jsonData.genres[1]).to.have.property('id');\r", + " pm.expect(jsonData.genres[1].id, '\"genres[1].id\" field must be 2').to.eql(2);\r", + " pm.expect(jsonData.genres[1]).to.have.property('name');\r", + " pm.expect(jsonData.genres[1].name, '\"genres[1].name\" field must be \"Драма\"').to.eql('Драма');\r", + "});" + ], + "type": "text/javascript", + "packages": {} + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " try {\r", + " film = await api.addFilm({\r", + " \"name\": \"New film\",\r", + " \"releaseDate\": \"1999-04-30\",\r", + " \"description\": \"New film about friends\",\r", + " \"duration\": 120,\r", + " \"mpa\": { \"id\": 3},\r", + " \"genres\": [{ \"id\": 1}, { \"id\": 2}, { \"id\": 1}]\r", + " });\r", + " pm.collectionVariables.set(\"id\", film.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript", + "packages": {} + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "*/*" + } + ], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "{{id}}", + "description": "(Required) " + } + ] + } + }, + "response": [ + { + "name": "OK", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Not Found", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Not Found", + "code": 404, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Conflict", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Conflict", + "code": 409, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + }, + { + "name": "Internal Server Error", + "originalRequest": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/films/:id", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "films", + ":id" + ], + "variable": [ + { + "key": "id", + "value": "-29029902", + "description": "(Required) " + } + ] + } + }, + "status": "Internal Server Error", + "code": 500, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Content-Type", + "value": "*/*" + } + ], + "cookie": [], + "body": "" + } + ] + } + ] + } + ], + "event": [ + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "exec": [ + "API = class {", + " constructor(postman, verbose = false, baseUrl = \"http://localhost:8080\") {", + " this.baseUrl = baseUrl;", + " this.pm = postman;", + " this._verbose = verbose;", + " }", + "", + " async addUser(user, verbose=null) {", + " return this.post(\"/users\", user, \"Ошибка при добавлении нового пользователя: \", verbose);", + " }", + "", + " async addFilm(film, verbose=null) {", + " return this.post(\"/films\", film, \"Ошибка при добавлении нового фильма: \", verbose);", + " }", + "", + " async addFriend(userId, friendId, verbose=null) {", + " return this.put(\"/users/\" + userId + '/friends/' + friendId, null, \"Ошибка при добавлении нового фильма: \", verbose);", + " }", + "", + " async addLike(filmId, userId, verbose=null) {", + " return this.put(\"/films/\" + filmId + '/like/' + userId, null, \"Ошибка при добавлении лайка на фильм: \", verbose);", + " }", + "", + " async getFriends(userId, verbose=null) {", + " return this.get('/users/' + userId + '/friends', null, \"Ошибка при поиске друзей по id пользователя\", verbose);", + " }", + "", + " async post(path, body, errorText = \"Ошибка при выполнении post-запроса: \", verbose=null) {", + " return this.sendRequest(\"POST\", path, body, errorText, verbose);", + " }", + "", + " async patch(path, body = null, errorText = \"Ошибка при выполнении patch-запроса: \", verbose=null) {", + " return this.sendRequest(\"PATCH\", path, body, errorText, verbose);", + " }", + "", + " async get(path, body = null, errorText = \"Ошибка при выполнении get-запроса: \", verbose=null) {", + " return this.sendRequest(\"GET\", path, body, errorText, verbose);", + " }", + "", + " async put(path, body = null, errorText = \"Ошибка при выполнении put-запроса: \", verbose=null) {", + " return this.sendRequest(\"PUT\", path, body, errorText, verbose);", + " }", + "", + " async sendRequest(method, path, body=null, errorText = \"Ошибка при выполнении запроса: \", verbose=null) {", + " return new Promise((resolve, reject) => {", + " verbose = verbose == null ? this._verbose : verbose;", + " const request = {", + " url: this.baseUrl + path,", + " method: method,", + " body: body == null ? \"\" : JSON.stringify(body),", + " header: { \"Content-Type\": \"application/json\" },", + " };", + " if(verbose) {", + " console.log(\"Отправляю запрос: \", request);", + " }", + "", + " try {", + " this.pm.sendRequest(request, (error, response) => {", + " if(error || (response.code >= 400 && response.code <= 599)) {", + " let err = error ? error : JSON.stringify(response.json());", + " console.error(\"При выполнении запроса к серверу возникла ошика.\\n\", err,", + " \"\\nДля отладки проблемы повторите такой же запрос к вашей программе \" + ", + " \"на локальном компьютере. Данные запроса:\\n\", JSON.stringify(request));", + "", + " reject(new Error(errorText + err));", + " }", + " if(verbose) {", + " console.log(\"Результат обработки запроса: код состояния - \", response.code, \", тело: \", response.json());", + " }", + " if (response.stream.length === 0){", + " resolve(null);", + " }else{", + " resolve(response.json());", + " }", + " });", + " ", + " } catch(err) {", + " if(verbose) {", + " console.error(errorText, err);", + " }", + " return Promise.reject(err);", + " }", + " });", + " }", + "};", + "", + "RandomUtils = class {", + " constructor() {}", + "", + " getUser() {", + " let date = new Date(new Date(1960, 0, 1).getTime() + Math.random() * (new Date(2010, 0, 1).getTime() - new Date(1960, 0, 1).getTime()));", + " return {", + " name: pm.variables.replaceIn('{{$randomFullName}}'),", + " login: this.getWord(10),", + " email: pm.variables.replaceIn('{{$randomEmail}}'),", + " birthday: date.toISOString().slice(0,10)", + " };", + " }", + "", + " getFilm() {", + " let date = new Date(new Date(1960, 0, 1).getTime() + Math.random() * (new Date(2010, 0, 1).getTime() - new Date(1960, 0, 1).getTime()));", + " return {", + " name: this.getWord(15),", + " description: this.getWord(50),", + " releaseDate: date.toISOString().slice(0,10),", + " duration: Math.floor(Math.random() * (180 - 60 + 1) + 60),", + " mpa: { id: Math.floor(Math.random() * (5 - 1 + 1) + 1)},", + " genres: [{ id: Math.floor(Math.random() * (6 - 1 + 1) + 1)}]", + " };", + " }", + "", + " getWord(length = 1) {", + " let result = '';", + " const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';", + " const charactersLength = characters.length;", + " let counter = 0;", + " while (counter < length) {", + " result += characters.charAt(Math.floor(Math.random() * charactersLength));", + " counter += 1;", + " }", + " return result;", + " }", + "", + "}" + ] + } + }, + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "" + ] + } + } + ], + "variable": [ + { + "key": "baseUrl", + "value": "http://localhost:8080", + "type": "string" + }, + { + "key": "id", + "value": "" + }, + { + "key": "friend_id", + "value": "" + }, + { + "key": "user_friends", + "value": "" + }, + { + "key": "user3_id", + "value": "" + }, + { + "key": "film", + "value": "" + }, + { + "key": "film1_id", + "value": "" + }, + { + "key": "film2_id", + "value": "" + }, + { + "key": "film3_id", + "value": "" + }, + { + "key": "source", + "value": "" + }, + { + "key": "user", + "value": "" + }, + { + "key": "film_id", + "value": "" + }, + { + "key": "new_user_info", + "value": "" + } + ] +} diff --git a/README.md b/README.md index 9f00859..c8ab348 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,28 @@ _java-filmorate_ # Рейтинг фильмов -### Согласно задания спринта № 11 +### Согласно задания спринта № 12 (добавление Базы данных) ## выполнено Филипповских Сергеем _**Когорта-53**_ -в файле PostmanSprint11_add-friends-likes.json находится скрипт для проверки API +![](/er_diagram_filmrate.png) + +Примеры запросов: +1. Получение пользователя с ID = 1: + SELECT * + FROM users + WHERE user_id = 1; + +2. Получение фильма с ID = 10: + SELECT * + FROM films + WHERE film_id = 10. + +3. Получение списка фильмов, понравившихся пользователю с ID = 5: + SELECT title + FROM films + WHERE film_id IN (SELECT film_id FROM likes WHERE user_id = 5); + +_**Для 12 спринта есть файла для проверки через postman: +PostmanSprint12_add-database.json**_ \ No newline at end of file diff --git a/er_diagram_filmrate.png b/er_diagram_filmrate.png new file mode 100644 index 0000000..d502bda Binary files /dev/null and b/er_diagram_filmrate.png differ diff --git a/pom.xml b/pom.xml index 57fafc4..60c5890 100644 --- a/pom.xml +++ b/pom.xml @@ -2,20 +2,24 @@ 4.0.0 + org.springframework.boot spring-boot-starter-parent - 3.2.4 - + 3.4.1 + + ru.yandex.practicum filmorate 0.0.1-SNAPSHOT filmorate filmorate + - 21 + 17 + org.springframework.boot @@ -38,9 +42,17 @@ org.zalando logbook-spring-boot-starter - 3.9.0 + 3.9.0 + + + org.springframework.boot + spring-boot-starter-jdbc + + + com.h2database + h2 + runtime - @@ -49,6 +61,29 @@ org.springframework.boot spring-boot-maven-plugin + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.6.0 + + checkstyle.xml + true + true + true + + + + + check + + compile + + + diff --git a/src/main/java/ru/yandex/practicum/filmorate/controller/ErrorHandler.java b/src/main/java/ru/yandex/practicum/filmorate/controller/ErrorHandler.java index 5694d83..94882a8 100644 --- a/src/main/java/ru/yandex/practicum/filmorate/controller/ErrorHandler.java +++ b/src/main/java/ru/yandex/practicum/filmorate/controller/ErrorHandler.java @@ -22,7 +22,7 @@ public class ErrorHandler { @ExceptionHandler @ResponseStatus(HttpStatus.BAD_REQUEST) public ErrorResponse handleValidationException(final ValidationException e) { - log.error(HttpStatus.BAD_REQUEST + " - " + e.getMessage()); + log.error("{} - {}", HttpStatus.BAD_REQUEST, e.getMessage()); return new ErrorResponse(e.getMessage()); } @@ -34,26 +34,26 @@ public ErrorResponse handleMethodArgumentNotValidException(final MethodArgumentN String defaultMessage = allErrors.stream() .map(error -> Objects.requireNonNull(error.getDefaultMessage())) .collect(Collectors.joining(", ")); - log.error(HttpStatus.BAD_REQUEST + " - " + defaultMessage); + log.error("{} - {}", HttpStatus.BAD_REQUEST, defaultMessage); return new ErrorResponse(defaultMessage); } @ExceptionHandler @ResponseStatus(HttpStatus.NOT_FOUND) public ErrorResponse handleNotFoundException(final NotFoundException e) { - log.error(HttpStatus.NOT_FOUND + " - " + e.getMessage()); + log.error("{} - {}", HttpStatus.NOT_FOUND, e.getMessage()); return new ErrorResponse(e.getMessage()); } @ExceptionHandler @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ErrorResponse handleRunTimeException(final RuntimeException e) { - log.error(HttpStatus.INTERNAL_SERVER_ERROR + " - " + e.getMessage()); + log.error("{} - {}", HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); return new ErrorResponse(e.getMessage()); } @Getter - private static class ErrorResponse { + public static class ErrorResponse { private final String error; public ErrorResponse(String error) { diff --git a/src/main/java/ru/yandex/practicum/filmorate/controller/FilmController.java b/src/main/java/ru/yandex/practicum/filmorate/controller/FilmController.java index 313431c..ff883bc 100644 --- a/src/main/java/ru/yandex/practicum/filmorate/controller/FilmController.java +++ b/src/main/java/ru/yandex/practicum/filmorate/controller/FilmController.java @@ -2,7 +2,6 @@ import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import ru.yandex.practicum.filmorate.model.Film; @@ -10,7 +9,6 @@ import java.util.List; -@Slf4j @RestController @RequestMapping("/films") @RequiredArgsConstructor @@ -18,7 +16,6 @@ public class FilmController { private final FilmService filmService; - // добавляем фильм @ResponseStatus(HttpStatus.CREATED) @PostMapping public Film create(@RequestBody @Valid Film film) { @@ -26,33 +23,28 @@ public Film create(@RequestBody @Valid Film film) { return film; } - // обновляем данные о фильме @PutMapping public Film update(@RequestBody @Valid Film film) { filmService.update(film); return film; } - // получаем список фильмов @GetMapping public List findAll() { return filmService.findAll(); } - // Получаем фильм по id @GetMapping("/{filmId}") public Film getFilmById(@PathVariable Integer filmId) { return filmService.getById(filmId); } - // Добавляем like пользователя userId к фильму filmId @PutMapping("/{filmId}/like/{userId}") public Film addLike(@PathVariable Integer filmId, @PathVariable Integer userId) { filmService.addLike(filmId, userId); return filmService.getById(filmId); } - // Удаляем like пользователя userId к фильму filmId @DeleteMapping("/{filmId}/like/{userId}") public Film deleteLike(@PathVariable Integer filmId, @PathVariable Integer userId) { filmService.deleteLike(filmId, userId); @@ -63,5 +55,4 @@ public Film deleteLike(@PathVariable Integer filmId, @PathVariable Integer userI public List getListBestFilms(@RequestParam(defaultValue = "10") Integer count) { return filmService.listBestFilms(count); } - } diff --git a/src/main/java/ru/yandex/practicum/filmorate/controller/GenreController.java b/src/main/java/ru/yandex/practicum/filmorate/controller/GenreController.java new file mode 100644 index 0000000..faf8ec4 --- /dev/null +++ b/src/main/java/ru/yandex/practicum/filmorate/controller/GenreController.java @@ -0,0 +1,25 @@ +package ru.yandex.practicum.filmorate.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; +import ru.yandex.practicum.filmorate.model.Genre; +import ru.yandex.practicum.filmorate.service.GenreService; + +import java.util.List; + +@RestController +@RequestMapping("/genres") +@RequiredArgsConstructor +public class GenreController { + private final GenreService genreService; + + @GetMapping + public List findAll() { + return genreService.findAll(); + } + + @GetMapping("/{id}") + public Genre getById(@PathVariable Integer id) { + return genreService.getById(id); + } +} diff --git a/src/main/java/ru/yandex/practicum/filmorate/controller/RatingController.java b/src/main/java/ru/yandex/practicum/filmorate/controller/RatingController.java new file mode 100644 index 0000000..7e4f481 --- /dev/null +++ b/src/main/java/ru/yandex/practicum/filmorate/controller/RatingController.java @@ -0,0 +1,28 @@ +package ru.yandex.practicum.filmorate.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import ru.yandex.practicum.filmorate.model.Rating; +import ru.yandex.practicum.filmorate.service.RatingService; + +import java.util.List; + +@RestController +@RequestMapping("/mpa") +@RequiredArgsConstructor +public class RatingController { + private final RatingService ratingService; + + @GetMapping + public List findAll() { + return ratingService.findAll(); + } + + @GetMapping("/{id}") + public Rating getById(@PathVariable Integer id) { + return ratingService.getById(id); + } +} diff --git a/src/main/java/ru/yandex/practicum/filmorate/controller/UserController.java b/src/main/java/ru/yandex/practicum/filmorate/controller/UserController.java index e63da94..97e15f3 100644 --- a/src/main/java/ru/yandex/practicum/filmorate/controller/UserController.java +++ b/src/main/java/ru/yandex/practicum/filmorate/controller/UserController.java @@ -2,7 +2,6 @@ import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import ru.yandex.practicum.filmorate.model.User; @@ -10,7 +9,6 @@ import java.util.List; -@Slf4j @RestController @RequestMapping("/users") @RequiredArgsConstructor @@ -18,7 +16,6 @@ public class UserController { private final UserService userService; - // Добавляем пользователя @ResponseStatus(HttpStatus.CREATED) @PostMapping public User create(@RequestBody @Valid User user) { @@ -26,46 +23,39 @@ public User create(@RequestBody @Valid User user) { return user; } - // Обновляем данные пользователя @PutMapping public User update(@RequestBody @Valid User user) { userService.update(user); return user; } - // Получаем список всех пользователей @GetMapping public List findAll() { return userService.findAll(); } - // Получаем пользователя по id @GetMapping("/{userId}") public User getUserById(@PathVariable Integer userId) { return userService.getById(userId); } - // Добавляем друга friendId для пользователя userId @PutMapping("/{userId}/friends/{friendId}") public User addFriend(@PathVariable Integer userId, @PathVariable Integer friendId) { userService.addFriend(userId, friendId); return userService.getById(userId); } - // Удаляем друга friendId у пользователя userId @DeleteMapping("/{userId}/friends/{friendId}") public User deleteFriend(@PathVariable Integer userId, @PathVariable Integer friendId) { userService.deleteFriend(userId, friendId); return userService.getById(userId); } - // Получаем список друзей пользователя userId @GetMapping("/{userId}/friends") public List getUserFriends(@PathVariable Integer userId) { return userService.userFriends(userId); } - // Получаем общий список друзей пользователя userId и и пользователя otherUserId @GetMapping("/{userId}/friends/common/{otherUserId}") public List getCrossingFriends(@PathVariable Integer userId, @PathVariable Integer otherUserId) { return userService.crossingFriends(userId, otherUserId); diff --git a/src/main/java/ru/yandex/practicum/filmorate/model/Film.java b/src/main/java/ru/yandex/practicum/filmorate/model/Film.java index 1c5b382..9b069ff 100644 --- a/src/main/java/ru/yandex/practicum/filmorate/model/Film.java +++ b/src/main/java/ru/yandex/practicum/filmorate/model/Film.java @@ -1,23 +1,22 @@ package ru.yandex.practicum.filmorate.model; - import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; import lombok.Data; -import lombok.extern.slf4j.Slf4j; -import java.time.LocalDate; -import java.util.HashSet; -import java.util.Set; +import java.sql.Date; +import java.util.ArrayList; +import java.util.List; @Data -@Slf4j public class Film { private Integer id; - private Set likes = new HashSet<>(); + private List likes = new ArrayList<>(); + + private List genres = new ArrayList<>(); @NotNull(message = "Необходимо указать название фильма") @NotBlank(message = "Название фильма не может быть пустым") @@ -26,12 +25,14 @@ public class Film { @Size(min = 1, max = 200, message = "Описание фильма должно быть от 1 до 200 символов") private String description; - @MinimumDate(message = "Фильм не может выйти в прокат ранее 28.12.1895") - private LocalDate releaseDate; - @NotNull(message = "Необходимо указать продолжительность фильма") @Min(value = 1, message = "Продолжительность фильма должна быть не меньше 1 секунды") - private int duration; + private Integer duration; + + @MinimumDate(message = "Фильм не может выйти в прокат ранее 28.12.1895") + private Date releaseDate; + + private Rating mpa; public void addLike(Integer id) { likes.add(id); @@ -40,4 +41,5 @@ public void addLike(Integer id) { public void removeLike(Integer id) { likes.remove(id); } + } diff --git a/src/main/java/ru/yandex/practicum/filmorate/model/Genre.java b/src/main/java/ru/yandex/practicum/filmorate/model/Genre.java new file mode 100644 index 0000000..e40c936 --- /dev/null +++ b/src/main/java/ru/yandex/practicum/filmorate/model/Genre.java @@ -0,0 +1,9 @@ +package ru.yandex.practicum.filmorate.model; + +import lombok.Data; + +@Data +public class Genre { + private Integer id; + private String name; +} diff --git a/src/main/java/ru/yandex/practicum/filmorate/model/MinimumDate.java b/src/main/java/ru/yandex/practicum/filmorate/model/MinimumDate.java index 404a22a..9bf0130 100644 --- a/src/main/java/ru/yandex/practicum/filmorate/model/MinimumDate.java +++ b/src/main/java/ru/yandex/practicum/filmorate/model/MinimumDate.java @@ -11,7 +11,9 @@ @Past public @interface MinimumDate { String message() default "Минимальная дата выхода фильма {value}"; + Class[] groups() default {}; + Class[] payload() default {}; String value() default "1895-12-28"; diff --git a/src/main/java/ru/yandex/practicum/filmorate/model/MinimumDateValidator.java b/src/main/java/ru/yandex/practicum/filmorate/model/MinimumDateValidator.java index 625440f..dad323b 100644 --- a/src/main/java/ru/yandex/practicum/filmorate/model/MinimumDateValidator.java +++ b/src/main/java/ru/yandex/practicum/filmorate/model/MinimumDateValidator.java @@ -3,18 +3,18 @@ import jakarta.validation.ConstraintValidator; import jakarta.validation.ConstraintValidatorContext; -import java.time.LocalDate; +import java.sql.Date; -public class MinimumDateValidator implements ConstraintValidator { - private LocalDate minimumDate; +public class MinimumDateValidator implements ConstraintValidator { + private Date minimumDate; @Override public void initialize(MinimumDate constraintAnnotation) { - minimumDate = LocalDate.parse(constraintAnnotation.value()); + minimumDate = Date.valueOf(constraintAnnotation.value()); } @Override - public boolean isValid(LocalDate value, ConstraintValidatorContext context) { - return value == null || !value.isBefore(minimumDate); + public boolean isValid(Date value, ConstraintValidatorContext constraintValidatorContext) { + return value != null && !value.before(minimumDate); } } diff --git a/src/main/java/ru/yandex/practicum/filmorate/model/Rating.java b/src/main/java/ru/yandex/practicum/filmorate/model/Rating.java new file mode 100644 index 0000000..b47d472 --- /dev/null +++ b/src/main/java/ru/yandex/practicum/filmorate/model/Rating.java @@ -0,0 +1,9 @@ +package ru.yandex.practicum.filmorate.model; + +import lombok.Data; + +@Data +public class Rating { + private Integer id; + private String name; +} \ No newline at end of file diff --git a/src/main/java/ru/yandex/practicum/filmorate/model/User.java b/src/main/java/ru/yandex/practicum/filmorate/model/User.java index 71c1c8c..7c05712 100644 --- a/src/main/java/ru/yandex/practicum/filmorate/model/User.java +++ b/src/main/java/ru/yandex/practicum/filmorate/model/User.java @@ -2,33 +2,31 @@ import jakarta.validation.constraints.*; import lombok.Data; -import lombok.extern.slf4j.Slf4j; -import java.time.LocalDate; -import java.util.HashSet; -import java.util.Set; +import java.sql.Date; +import java.util.ArrayList; +import java.util.List; @Data -@Slf4j public class User { private Integer id; - private Set friends = new HashSet<>(); - - @Email(message = "Укажите корректный email") - @NotNull(message = "Необходимо указать email") - @NotBlank(message = "Email не может быть пустым") - private String email; + private List friends = new ArrayList<>(); @NotNull(message = "Необходимо указать логин") @NotBlank(message = "Логин не может быть пустым") @Pattern(regexp = "^[A-Za-z0-9]+$", message = "Логин может содержать только буквы и цифры без пробелов и спецсимволов") private String login; + @Email(message = "Укажите корректный email") + @NotNull(message = "Необходимо указать email") + @NotBlank(message = "Email не может быть пустым") + private String email; + private String name; @PastOrPresent(message = "Дата рождения не должна находиться в будущем") - private LocalDate birthday; + private Date birthday; public void addFriend(Integer id) { friends.add(id); diff --git a/src/main/java/ru/yandex/practicum/filmorate/service/FilmService.java b/src/main/java/ru/yandex/practicum/filmorate/service/FilmService.java index a925140..190cbdf 100644 --- a/src/main/java/ru/yandex/practicum/filmorate/service/FilmService.java +++ b/src/main/java/ru/yandex/practicum/filmorate/service/FilmService.java @@ -6,7 +6,8 @@ import ru.yandex.practicum.filmorate.exception.NotFoundException; import ru.yandex.practicum.filmorate.exception.ValidationException; import ru.yandex.practicum.filmorate.model.Film; -import ru.yandex.practicum.filmorate.storage.FilmStorage; +import ru.yandex.practicum.filmorate.storage.FilmDbStorage; +import ru.yandex.practicum.filmorate.storage.LikeDbStorage; import ru.yandex.practicum.filmorate.storage.UserStorage; import java.util.List; @@ -16,46 +17,50 @@ @Service @RequiredArgsConstructor public class FilmService { - private final FilmStorage filmStorage; + private final FilmDbStorage filmStorage; private final UserStorage userStorage; + private final LikeDbStorage likeStorage; public Film create(Film film) { + log.info("create film with id: {}", film.getId()); return filmStorage.create(film); } public Film update(Film film) { + log.info("update film with id: {}", film.getId()); return filmStorage.update(film); } public Film getById(Integer id) { + log.info("get film by id: {}", id); return filmStorage.getById(id); } public List findAll() { + log.info("get all films"); return filmStorage.findAll(); } - // Ставим лайк фильму public void addLike(Integer idFilm, Integer idUser) { checkForLike(idFilm, idUser); - filmStorage.getById(idFilm).addLike(idUser); + log.info("add like film with id: {} and user with id: {}", idFilm, idUser); + likeStorage.addLike(idFilm, idUser); } - // Убираем лайк фильму public void deleteLike(Integer idFilm, Integer idUser) { checkForLike(idFilm, idUser); - filmStorage.getById(idFilm).removeLike(idUser); + log.info("delete like film with id: {} and user with id: {}", idFilm, idUser); + likeStorage.deleteLike(idFilm, idUser); } - // Получаем список лучших фильмов public List listBestFilms(int count) { + log.info("list best films"); return filmStorage.findAll().stream() - .sorted((f1, f2) -> f2.getLikes().size() - f1.getLikes().size()) - .limit(count) - .collect(Collectors.toList()); + .sorted((f1, f2) -> f2.getLikes().size() - f1.getLikes().size()) + .limit(count) + .collect(Collectors.toList()); } - // проверка условий для установки и удаления лайка private void checkForLike(Integer idFilm, Integer idUser) { if (idFilm == null) { throw new ValidationException("Не указан id фильма"); diff --git a/src/main/java/ru/yandex/practicum/filmorate/service/GenreService.java b/src/main/java/ru/yandex/practicum/filmorate/service/GenreService.java new file mode 100644 index 0000000..4a3418a --- /dev/null +++ b/src/main/java/ru/yandex/practicum/filmorate/service/GenreService.java @@ -0,0 +1,26 @@ +package ru.yandex.practicum.filmorate.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import ru.yandex.practicum.filmorate.model.Genre; +import ru.yandex.practicum.filmorate.storage.GenreDbStorage; + +import java.util.List; + +@Slf4j +@Service +@RequiredArgsConstructor +public class GenreService { + private final GenreDbStorage genreStorage; + + public Genre getById(Integer id) { + log.info("get genre by id: {}", id); + return genreStorage.getById(id); + } + + public List findAll() { + log.info("get all genres"); + return genreStorage.findAll(); + } +} diff --git a/src/main/java/ru/yandex/practicum/filmorate/service/RatingService.java b/src/main/java/ru/yandex/practicum/filmorate/service/RatingService.java new file mode 100644 index 0000000..50c64b4 --- /dev/null +++ b/src/main/java/ru/yandex/practicum/filmorate/service/RatingService.java @@ -0,0 +1,26 @@ +package ru.yandex.practicum.filmorate.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import ru.yandex.practicum.filmorate.model.Rating; +import ru.yandex.practicum.filmorate.storage.RatingDbStorage; + +import java.util.List; + +@Slf4j +@Service +@RequiredArgsConstructor +public class RatingService { + private final RatingDbStorage ratingStorage; + + public Rating getById(Integer id) { + log.info("get rating by id: {}", id); + return ratingStorage.getById(id); + } + + public List findAll() { + log.info("get all ratings"); + return ratingStorage.findAll(); + } +} \ No newline at end of file diff --git a/src/main/java/ru/yandex/practicum/filmorate/service/UserService.java b/src/main/java/ru/yandex/practicum/filmorate/service/UserService.java index d30b7bb..734dde4 100644 --- a/src/main/java/ru/yandex/practicum/filmorate/service/UserService.java +++ b/src/main/java/ru/yandex/practicum/filmorate/service/UserService.java @@ -6,7 +6,8 @@ import ru.yandex.practicum.filmorate.exception.NotFoundException; import ru.yandex.practicum.filmorate.exception.ValidationException; import ru.yandex.practicum.filmorate.model.User; -import ru.yandex.practicum.filmorate.storage.UserStorage; +import ru.yandex.practicum.filmorate.storage.FriendDbStorage; +import ru.yandex.practicum.filmorate.storage.UserDbStorage; import java.util.HashSet; import java.util.List; @@ -17,62 +18,63 @@ @Service @RequiredArgsConstructor public class UserService { - - private final UserStorage userStorage; + private final UserDbStorage userStorage; + private final FriendDbStorage friendStorage; public User create(User user) { + log.info("create user with id: {}", user.getId()); return userStorage.create(user); } public User update(User user) { + log.info("update user with id: {}", user.getId()); return userStorage.update(user); } public User getById(Integer id) { + log.info("get user by id: {}", id); return userStorage.getById(id); } public List findAll() { + log.info("get all users"); return userStorage.findAll(); } - // Добавляем друга в список друзей public void addFriend(Integer idUser, Integer idFriend) { if (idUser.equals(idFriend)) { throw new ValidationException("Нельзя добавить себя в друзья"); } checkForFriend(idUser, idFriend); - userStorage.getById(idUser).addFriend(idFriend); - userStorage.getById(idFriend).addFriend(idUser); + log.info("add friend with idUser: {}, idFriend: {}", idUser, idFriend); + friendStorage.addFriend(idUser, idFriend); } - // Удаляем друга из списка друзей public void deleteFriend(Integer idUser, Integer idFriend) { checkForFriend(idUser, idFriend); - userStorage.getById(idUser).removeFriend(idFriend); - userStorage.getById(idFriend).removeFriend(idUser); + log.info("delete friend with idUser: {}, idFriend: {}", idUser, idFriend); + friendStorage.deleteFriend(idUser, idFriend); } - // Получаем список друзей public List userFriends(Integer idUser) { - User user = userStorage.getById(idUser); - return userStorage.findAll().stream() - .filter(u -> user.getFriends().contains(u.getId())) - .collect(Collectors.toList()); + if (userStorage.getById(idUser) == null) { + throw new NotFoundException("Пользователь с id = " + idUser + " не найден"); + } + log.info("get user friends with idUser: {}", idUser); + return userStorage.getFriends(idUser); } - // Получаем общий список друзей public List crossingFriends(Integer idUser, Integer idFriend) { User user = userStorage.getById(idUser); User friend = userStorage.getById(idFriend); Set commonFriends = new HashSet<>(user.getFriends()); commonFriends.retainAll(friend.getFriends()); + log.info("get common friends with idUser: {}, idFriend: {}", idUser, idFriend); return userStorage.findAll().stream() .filter(u -> commonFriends.contains(u.getId())) .collect(Collectors.toList()); } - // Проверка для установки или удаления друзей private void checkForFriend(Integer idUser, Integer idFriend) { if (idUser == null || idFriend == null) { throw new ValidationException("Не указаны id пользователя или его друга"); diff --git a/src/main/java/ru/yandex/practicum/filmorate/storage/FilmDbStorage.java b/src/main/java/ru/yandex/practicum/filmorate/storage/FilmDbStorage.java new file mode 100644 index 0000000..67bdf64 --- /dev/null +++ b/src/main/java/ru/yandex/practicum/filmorate/storage/FilmDbStorage.java @@ -0,0 +1,104 @@ +package ru.yandex.practicum.filmorate.storage; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Primary; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Repository; +import ru.yandex.practicum.filmorate.exception.NotFoundException; +import ru.yandex.practicum.filmorate.model.Film; +import ru.yandex.practicum.filmorate.model.Genre; +import ru.yandex.practicum.filmorate.storage.dbmapper.FilmRowMapper; + +import java.sql.PreparedStatement; +import java.sql.Statement; +import java.util.List; +import java.util.Objects; + +@Slf4j +@Primary +@Repository +@RequiredArgsConstructor +public class FilmDbStorage implements FilmStorage { + private final JdbcTemplate jdbc; + private final FilmRowMapper filmRowMapper; + + @Override + public Film create(Film film) { + List ratings = jdbc.queryForList("SELECT id FROM mpa", Integer.class); + List genres = jdbc.queryForList("SELECT id FROM genres", Integer.class); + + if (!ratings.contains(film.getMpa().getId())) { + throw new NotFoundException("Рейтинг MPA с id " + film.getMpa().getId() + " не найден"); + } + + List notFoundGenres = film.getGenres().stream() + .map(Genre::getId) + .filter(id -> !genres.contains(id)) + .toList(); + + if (!notFoundGenres.isEmpty()) { + throw new NotFoundException("Жанры с id " + notFoundGenres + " не найдены"); + } + + KeyHolder keyHolder = new GeneratedKeyHolder(); + jdbc.update(connection -> { + PreparedStatement ps = connection + .prepareStatement("INSERT INTO films (name, description, duration, release_date, mpa) VALUES (?, ?, ?, ?, ?)", + Statement.RETURN_GENERATED_KEYS); + ps.setString(1, film.getName()); + ps.setString(2, film.getDescription()); + ps.setInt(3, film.getDuration()); + ps.setDate(4, film.getReleaseDate()); + ps.setObject(5, film.getMpa().getId()); + return ps; + }, keyHolder); + film.setId(Objects.requireNonNull(keyHolder.getKey()).intValue()); + for (Genre genre : film.getGenres()) { + try { + jdbc.update("INSERT INTO film_genres (film_id, genre_id) VALUES (?, ?)", + keyHolder.getKey().intValue(), genre.getId()); + } catch (DuplicateKeyException e) { + log.error("Duplicate key exception"); + } + } + return film; + } + + @Override + public Film update(Film film) { + int count = jdbc.update("UPDATE films SET name = ?, description = ?, duration = ?, release_date = ?, mpa = ? WHERE id = ?", + film.getName(), film.getDescription(), film.getDuration(), film.getReleaseDate(), film.getMpa().getId(), film.getId()); + if (count == 0) { + throw new NotFoundException("Фильм с id " + film.getId() + " не найден"); + } + jdbc.update("DELETE FROM film_genres WHERE film_id = ?", film.getId()); + for (Genre genre : film.getGenres()) { + try { + jdbc.update("INSERT INTO film_genres (film_id, genre_id) VALUES (?, ?)", + film.getId(), genre.getId()); + } catch (DuplicateKeyException e) { + log.error("Duplicate key exception"); + } + } + return film; + } + + @Override + public List findAll() { + return jdbc.query("SELECT * FROM films", filmRowMapper); + } + + @Override + public Film getById(Integer id) { + try { + return jdbc.queryForObject("SELECT * FROM films WHERE id = ?", filmRowMapper, id); + } catch (EmptyResultDataAccessException e) { + throw new NotFoundException("Фильм с id " + id + " не найден"); + } + } +} diff --git a/src/main/java/ru/yandex/practicum/filmorate/storage/FriendDbStorage.java b/src/main/java/ru/yandex/practicum/filmorate/storage/FriendDbStorage.java new file mode 100644 index 0000000..2cdf657 --- /dev/null +++ b/src/main/java/ru/yandex/practicum/filmorate/storage/FriendDbStorage.java @@ -0,0 +1,35 @@ +package ru.yandex.practicum.filmorate.storage; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Primary; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Slf4j +@Primary +@Repository +@RequiredArgsConstructor +public class FriendDbStorage { + private final JdbcTemplate jdbc; + + public void addFriend(Integer userId, Integer friendId) { + try { + jdbc.update("INSERT INTO friends (user_id, friend_id) VALUES (?, ?)", userId, friendId); + } catch (DuplicateKeyException e) { + log.error("DuplicateKeyException"); + } + } + + public void deleteFriend(Integer userId, Integer friendId) { + jdbc.update("DELETE FROM friends WHERE user_id = ? AND friend_id = ?", userId, friendId); + } + + public List getFriends(Integer userId) { + return jdbc.queryForList("SELECT friend_id FROM friends WHERE user_id = ?", + Integer.class, userId); + } +} diff --git a/src/main/java/ru/yandex/practicum/filmorate/storage/GenreDbStorage.java b/src/main/java/ru/yandex/practicum/filmorate/storage/GenreDbStorage.java new file mode 100644 index 0000000..f0504ab --- /dev/null +++ b/src/main/java/ru/yandex/practicum/filmorate/storage/GenreDbStorage.java @@ -0,0 +1,37 @@ +package ru.yandex.practicum.filmorate.storage; + +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Primary; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; +import ru.yandex.practicum.filmorate.exception.NotFoundException; +import ru.yandex.practicum.filmorate.model.Genre; +import ru.yandex.practicum.filmorate.storage.dbmapper.GenreRowMapper; + +import java.util.List; + +@Primary +@Repository +@RequiredArgsConstructor +public class GenreDbStorage { + private final JdbcTemplate jdbc; + private final GenreRowMapper genreRowMapper; + + public List findAll() { + return jdbc.query("SELECT * FROM genres", genreRowMapper); + } + + public Genre getById(Integer id) { + try { + return jdbc.queryForObject("SELECT * FROM genres WHERE id = ?", genreRowMapper, id); + } catch (EmptyResultDataAccessException e) { + throw new NotFoundException("Жанр с id " + id + " не найден"); + } + } + + public List getByFilmId(Integer filmId) { + return jdbc.query("SELECT * FROM genres WHERE id IN (SELECT genre_id FROM film_genres WHERE film_id = ?)", + genreRowMapper, filmId); + } +} diff --git a/src/main/java/ru/yandex/practicum/filmorate/storage/InMemoryFilmStorage.java b/src/main/java/ru/yandex/practicum/filmorate/storage/InMemoryFilmStorage.java index f20811e..3a8397a 100644 --- a/src/main/java/ru/yandex/practicum/filmorate/storage/InMemoryFilmStorage.java +++ b/src/main/java/ru/yandex/practicum/filmorate/storage/InMemoryFilmStorage.java @@ -1,7 +1,6 @@ package ru.yandex.practicum.filmorate.storage; import lombok.extern.slf4j.Slf4j; -import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Repository; import ru.yandex.practicum.filmorate.exception.NotFoundException; import ru.yandex.practicum.filmorate.exception.ValidationException; @@ -12,8 +11,7 @@ import java.util.Map; @Slf4j -@Repository("inMemoryFilmStorage") -@Primary +@Repository public class InMemoryFilmStorage implements FilmStorage { private final Map films = new HashMap<>(); diff --git a/src/main/java/ru/yandex/practicum/filmorate/storage/InMemoryUserStorage.java b/src/main/java/ru/yandex/practicum/filmorate/storage/InMemoryUserStorage.java index de24788..8b92e94 100644 --- a/src/main/java/ru/yandex/practicum/filmorate/storage/InMemoryUserStorage.java +++ b/src/main/java/ru/yandex/practicum/filmorate/storage/InMemoryUserStorage.java @@ -1,7 +1,6 @@ package ru.yandex.practicum.filmorate.storage; import lombok.extern.slf4j.Slf4j; -import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Repository; import ru.yandex.practicum.filmorate.exception.NotFoundException; import ru.yandex.practicum.filmorate.exception.ValidationException; @@ -12,8 +11,7 @@ import java.util.Map; @Slf4j -@Repository("inMemoryUserStorage") -@Primary +@Repository public class InMemoryUserStorage implements UserStorage { private final Map users = new HashMap<>(); diff --git a/src/main/java/ru/yandex/practicum/filmorate/storage/LikeDbStorage.java b/src/main/java/ru/yandex/practicum/filmorate/storage/LikeDbStorage.java new file mode 100644 index 0000000..608ef87 --- /dev/null +++ b/src/main/java/ru/yandex/practicum/filmorate/storage/LikeDbStorage.java @@ -0,0 +1,35 @@ +package ru.yandex.practicum.filmorate.storage; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Primary; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Slf4j +@Primary +@Repository +@RequiredArgsConstructor +public class LikeDbStorage { + private final JdbcTemplate jdbc; + + public void addLike(Integer filmId, Integer userId) { + try { + jdbc.update("INSERT INTO likes (film_id, user_id) VALUES (?, ?)", filmId, userId); + } catch (DuplicateKeyException e) { + log.error("DuplicateKeyException"); + } + } + + public void deleteLike(Integer filmId, Integer userId) { + jdbc.update("DELETE FROM likes WHERE film_id = ? AND user_id = ?", filmId, userId); + } + + public List getLikes(Integer filmId) { + return jdbc.queryForList("SELECT user_id FROM likes WHERE film_id = ?", + Integer.class, filmId); + } +} diff --git a/src/main/java/ru/yandex/practicum/filmorate/storage/RatingDbStorage.java b/src/main/java/ru/yandex/practicum/filmorate/storage/RatingDbStorage.java new file mode 100644 index 0000000..a8af3b4 --- /dev/null +++ b/src/main/java/ru/yandex/practicum/filmorate/storage/RatingDbStorage.java @@ -0,0 +1,34 @@ +package ru.yandex.practicum.filmorate.storage; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Primary; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; +import ru.yandex.practicum.filmorate.exception.NotFoundException; +import ru.yandex.practicum.filmorate.model.Rating; +import ru.yandex.practicum.filmorate.storage.dbmapper.RatingRowMapper; + +import java.util.List; + +@Slf4j +@Primary +@Repository +@RequiredArgsConstructor +public class RatingDbStorage { + private final JdbcTemplate jdbc; + private final RatingRowMapper ratingRowMapper; + + public List findAll() { + return jdbc.query("SELECT * FROM mpa", ratingRowMapper); + } + + public Rating getById(Integer id) { + try { + return jdbc.queryForObject("SELECT * FROM mpa WHERE id = ?", ratingRowMapper, id); + } catch (EmptyResultDataAccessException e) { + throw new NotFoundException("Рейтинг с id " + id + " не найден"); + } + } +} \ No newline at end of file diff --git a/src/main/java/ru/yandex/practicum/filmorate/storage/UserDbStorage.java b/src/main/java/ru/yandex/practicum/filmorate/storage/UserDbStorage.java new file mode 100644 index 0000000..7ccfd21 --- /dev/null +++ b/src/main/java/ru/yandex/practicum/filmorate/storage/UserDbStorage.java @@ -0,0 +1,71 @@ +package ru.yandex.practicum.filmorate.storage; + +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Primary; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Repository; +import ru.yandex.practicum.filmorate.exception.NotFoundException; +import ru.yandex.practicum.filmorate.model.User; +import ru.yandex.practicum.filmorate.storage.dbmapper.UserRowMapper; + +import java.sql.PreparedStatement; +import java.sql.Statement; +import java.util.List; +import java.util.Objects; + +@Primary +@Repository +@RequiredArgsConstructor +public class UserDbStorage implements UserStorage { + private final JdbcTemplate jdbc; + private final UserRowMapper userRowMapper; + + @Override + public User create(User user) { + KeyHolder keyHolder = new GeneratedKeyHolder(); + jdbc.update(connection -> { + PreparedStatement ps = connection + .prepareStatement("INSERT INTO users (login, email, name, birthday) VALUES (?, ?, ?, ?)", + Statement.RETURN_GENERATED_KEYS); + ps.setString(3, user.getLogin()); + ps.setString(2, user.getEmail()); + ps.setString(1, user.getName()); + ps.setDate(4, user.getBirthday()); + return ps; + }, keyHolder); + user.setId(Objects.requireNonNull(keyHolder.getKey()).intValue()); + return user; + } + + @Override + public User update(User user) { + int count = jdbc.update("UPDATE users SET login = ?, email = ?, name = ?, birthday = ? WHERE id = ?", + user.getLogin(), user.getEmail(), user.getName(), user.getBirthday(), user.getId()); + if (count == 0) { + throw new NotFoundException("Пользователь с id " + user.getId() + " не найден"); + } + return user; + } + + @Override + public List findAll() { + return jdbc.query("SELECT * FROM users", userRowMapper); + } + + @Override + public User getById(Integer id) { + try { + return jdbc.queryForObject("SELECT * FROM users WHERE id = ?", userRowMapper, id); + } catch (EmptyResultDataAccessException e) { + throw new NotFoundException("Пользователь с id " + id + " не найден"); + } + } + + public List getFriends(Integer id) { + return jdbc.query("SELECT * FROM users WHERE id IN (SELECT friend_id FROM friends WHERE user_id = ?)", + userRowMapper, id); + } +} diff --git a/src/main/java/ru/yandex/practicum/filmorate/storage/dbmapper/FilmRowMapper.java b/src/main/java/ru/yandex/practicum/filmorate/storage/dbmapper/FilmRowMapper.java new file mode 100644 index 0000000..32abdd7 --- /dev/null +++ b/src/main/java/ru/yandex/practicum/filmorate/storage/dbmapper/FilmRowMapper.java @@ -0,0 +1,34 @@ +package ru.yandex.practicum.filmorate.storage.dbmapper; + +import lombok.RequiredArgsConstructor; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.stereotype.Component; +import ru.yandex.practicum.filmorate.model.Film; +import ru.yandex.practicum.filmorate.storage.GenreDbStorage; +import ru.yandex.practicum.filmorate.storage.LikeDbStorage; +import ru.yandex.practicum.filmorate.storage.RatingDbStorage; + +import java.sql.ResultSet; +import java.sql.SQLException; + +@Component +@RequiredArgsConstructor +public class FilmRowMapper implements RowMapper { + private final RatingDbStorage ratingDbStorage; + private final LikeDbStorage likeDbStorage; + private final GenreDbStorage genreDbStorage; + + @Override + public Film mapRow(ResultSet resultSet, int rowNum) throws SQLException { + Film film = new Film(); + film.setId(resultSet.getInt("id")); + film.setName(resultSet.getString("name")); + film.setDescription(resultSet.getString("description")); + film.setDuration(resultSet.getInt("duration")); + film.setReleaseDate(resultSet.getDate("release_date")); + film.setMpa(ratingDbStorage.getById(resultSet.getInt("mpa"))); + film.setLikes(likeDbStorage.getLikes(resultSet.getInt("id"))); + film.setGenres(genreDbStorage.getByFilmId(resultSet.getInt("id"))); + return film; + } +} \ No newline at end of file diff --git a/src/main/java/ru/yandex/practicum/filmorate/storage/dbmapper/GenreRowMapper.java b/src/main/java/ru/yandex/practicum/filmorate/storage/dbmapper/GenreRowMapper.java new file mode 100644 index 0000000..6947168 --- /dev/null +++ b/src/main/java/ru/yandex/practicum/filmorate/storage/dbmapper/GenreRowMapper.java @@ -0,0 +1,20 @@ +package ru.yandex.practicum.filmorate.storage.dbmapper; + +import org.springframework.jdbc.core.RowMapper; +import org.springframework.stereotype.Component; +import ru.yandex.practicum.filmorate.model.Genre; + +import java.sql.ResultSet; +import java.sql.SQLException; + +@Component +public class GenreRowMapper implements RowMapper { + + @Override + public Genre mapRow(ResultSet resultSet, int rowNum) throws SQLException { + Genre genre = new Genre(); + genre.setId(resultSet.getInt("id")); + genre.setName(resultSet.getString("name")); + return genre; + } +} \ No newline at end of file diff --git a/src/main/java/ru/yandex/practicum/filmorate/storage/dbmapper/RatingRowMapper.java b/src/main/java/ru/yandex/practicum/filmorate/storage/dbmapper/RatingRowMapper.java new file mode 100644 index 0000000..09bd489 --- /dev/null +++ b/src/main/java/ru/yandex/practicum/filmorate/storage/dbmapper/RatingRowMapper.java @@ -0,0 +1,20 @@ +package ru.yandex.practicum.filmorate.storage.dbmapper; + +import org.springframework.jdbc.core.RowMapper; +import org.springframework.stereotype.Component; +import ru.yandex.practicum.filmorate.model.Rating; + +import java.sql.ResultSet; +import java.sql.SQLException; + +@Component +public class RatingRowMapper implements RowMapper { + + @Override + public Rating mapRow(ResultSet resultSet, int rowNum) throws SQLException { + Rating rating = new Rating(); + rating.setId(resultSet.getInt("id")); + rating.setName(resultSet.getString("name")); + return rating; + } +} \ No newline at end of file diff --git a/src/main/java/ru/yandex/practicum/filmorate/storage/dbmapper/UserRowMapper.java b/src/main/java/ru/yandex/practicum/filmorate/storage/dbmapper/UserRowMapper.java new file mode 100644 index 0000000..c622d66 --- /dev/null +++ b/src/main/java/ru/yandex/practicum/filmorate/storage/dbmapper/UserRowMapper.java @@ -0,0 +1,30 @@ +package ru.yandex.practicum.filmorate.storage.dbmapper; + +import lombok.RequiredArgsConstructor; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.stereotype.Component; +import ru.yandex.practicum.filmorate.model.User; +import ru.yandex.practicum.filmorate.storage.FriendDbStorage; + +import java.sql.ResultSet; +import java.sql.SQLException; + +@Component +@RequiredArgsConstructor +public class UserRowMapper implements RowMapper { + private final FriendDbStorage friendDbStorage; + + @Override + public User mapRow(ResultSet resultSet, int rowNum) throws SQLException { + User user = new User(); + user.setId(resultSet.getInt("id")); + user.setName(resultSet.getString("name")); + user.setLogin(resultSet.getString("login")); + user.setEmail(resultSet.getString("email")); + user.setBirthday(resultSet.getDate("birthday")); + user.setFriends(friendDbStorage.getFriends(resultSet.getInt("id"))); + return user; + } + + +} \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 92ee3fc..3cf419c 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1 +1,7 @@ logging.level.org.zalando.logbook= ERROR +spring.sql.init.mode=always +spring.datasource.url=jdbc:h2:file:./db/filmorate +spring.datasource.driverClassName=org.h2.Driver +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.datasource.username=sa +spring.datasource.password=password \ No newline at end of file diff --git a/src/main/resources/data.sql b/src/main/resources/data.sql new file mode 100644 index 0000000..6e666b5 --- /dev/null +++ b/src/main/resources/data.sql @@ -0,0 +1,14 @@ +MERGE INTO genres (id, name) + VALUES (1, 'Комедия'), + (2, 'Драма'), + (3, 'Мультфильм'), + (4, 'Триллер'), + (5, 'Документальный'), + (6, 'Боевик'); + +MERGE INTO mpa (id, name) + VALUES (1, 'G'), + (2, 'PG'), + (3, 'PG-13'), + (4, 'R'), + (5, 'NC-17'); \ No newline at end of file diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql new file mode 100644 index 0000000..6ed3a5d --- /dev/null +++ b/src/main/resources/schema.sql @@ -0,0 +1,54 @@ +DROP TABLE IF EXISTS film_genres; +DROP TABLE IF EXISTS friends; +DROP TABLE IF EXISTS likes; +DROP TABLE IF EXISTS genres; +DROP TABLE IF EXISTS users; +DROP TABLE IF EXISTS films; +DROP TABLE IF EXISTS mpa; + + + +CREATE TABLE IF NOT EXISTS genres ( + id INT NOT NULL GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + name VARCHAR(50) NOT NULL +); + +CREATE TABLE IF NOT EXISTS mpa ( + id INT NOT NULL GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + name VARCHAR(10) NOT NULL +); + +CREATE TABLE IF NOT EXISTS films ( + id INT NOT NULL GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + name VARCHAR(100) NOT NULL, + description VARCHAR(255), + duration INT NOT NULL, + release_date DATE NOT NULL, + mpa INT REFERENCES mpa(id) ON DELETE RESTRICT ON UPDATE CASCADE +); + +CREATE TABLE IF NOT EXISTS users ( + id INT NOT NULL GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + login VARCHAR(50) NOT NULL, + email VARCHAR(100) NOT NULL, + name VARCHAR(100), + birthday DATE +); + +CREATE TABLE IF NOT EXISTS film_genres ( + film_id INT NOT NULL REFERENCES films (id) ON DELETE CASCADE ON UPDATE CASCADE, + genre_id INT NOT NULL REFERENCES genres (id) ON DELETE CASCADE ON UPDATE CASCADE, + PRIMARY KEY (film_id, genre_id) +); + +CREATE TABLE IF NOT EXISTS likes ( + film_id INT NOT NULL REFERENCES films (id) ON DELETE CASCADE ON UPDATE CASCADE, + user_id INT NOT NULL REFERENCES users (id) ON DELETE RESTRICT ON UPDATE CASCADE, + PRIMARY KEY (film_id, user_id) +); + +CREATE TABLE IF NOT EXISTS friends ( + user_id INT NOT NULL REFERENCES users (id) ON DELETE CASCADE ON UPDATE CASCADE, + friend_id INT NOT NULL REFERENCES users (id) ON DELETE CASCADE ON UPDATE CASCADE, + PRIMARY KEY (user_id, friend_id) +); \ No newline at end of file diff --git a/src/test/java/ru/yandex/practicum/filmorate/FilmorateApplicationTests.java b/src/test/java/ru/yandex/practicum/filmorate/FilmorateApplicationTests.java index 7f2b8d9..e1aa6f8 100644 --- a/src/test/java/ru/yandex/practicum/filmorate/FilmorateApplicationTests.java +++ b/src/test/java/ru/yandex/practicum/filmorate/FilmorateApplicationTests.java @@ -6,5 +6,3 @@ public class FilmorateApplicationTests { } - -