inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

172만명의 커뮤니티!! 함께 토론해봐요.

섹션8 - Spring REST Docs

미해결

Practical Testing: 실용적인 테스트 가이드

학습 관련 질문을 남겨주세요. 어떤 부분이 고민인지, 무엇이 문제인지 상세히 작성하면 더 좋아요! 먼저 유사한 질문이 있었는지 검색해 보세요. 서로 예의를 지키며 존중하는 문화를 만들어가요. 안녕하세요. 강의를 100% 다 소화하지는 못했지만 일단 거진 한바퀴는 돌리면서 마지막에 문제가 생겨 질문 드립니다. plugins { id 'java' id 'org.springframework.boot' version '2.7.7' id 'io.spring.dependency-management' version '1.0.15.RELEASE' id "org.asciidoctor.jvm.convert" version "3.3.2" } group = 'sample' version = '0.0.1-SNAPSHOT' java { sourceCompatibility = '11' } configurations { compileOnly { extendsFrom annotationProcessor } asciidoctorExt } repositories { mavenCentral() } dependencies { // Spring boot implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-validation' // test testImplementation 'org.springframework.boot:spring-boot-starter-test' // lombok compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok' //테스트에서 lombok 사용 testCompileOnly 'org.projectlombok:lombok' testAnnotationProcessor 'org.projectlombok:lombok' // h2 runtimeOnly 'com.h2database:h2' // Guava implementation("com.google.guava:guava:32.1.1-jre") // RestDocs asciidoctorExt 'org.springframework.restdocs:spring-restdocs-asciidoctor' testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' } tasks.named('test') { useJUnitPlatform() } ext { // 전역 변수 snippetsDir = file('build/generated-snippets') } test { outputs.dir snippetsDir } asciidoctor { inputs.dir snippetsDir configurations 'asciidoctorExt' sources { include("**/index.adoc") } baseDirFollowsSourceDir() dependsOn test } bootJar { dependsOn asciidoctor from ("${asciidoctor.outputDir}") { into 'static/docs' } } 일단 build.gradle 내용이구요. 운영체제는 윈도우 입니다. 마지막에 build 후 jar파일을 실행하여 localhost:8080/docs/index.html 을 확인해보려고 하니 접속이 되지 않아 확인해보니 resources - static 디렉토리에 index.html이 생성되지 않았음을 확인하였습니다. build 디렉토리에는 생성되어 있었구요. 몇번이나 clean 후 build를 통해 build쪽에는 index.html이 생성 되는 것을 확인 하였으나, static 패키지 하위에 docs 패키지 조차 생성되지 않아 제가 뭔가 오타를 낸건지 운영체제 문제인지 질문 드리고자 합니다. 감사합니다.

  • spring
  • tdd
  • jpa
  • mockito
  • 소프트웨어-테스트
  • junit5
댓글 3 좋아요 2 조회수 1366

setValue가 함수가 아니라는 오류 발생

미해결

따라하며 배우는 리액트 A-Z[19버전 반영]

TailwindCss 적용하기 실습 중 발생한 문제입니다. setValue is not a function TypeError: setValue is not a function at handleChange ( http://localhost:3000/static/js/bundle.js:167:5 ) at HTMLUnknownElement.callCallback ( http://localhost:3000/static/js/bundle.js:11038:18 ) at Object.invokeGuardedCallbackDev ( http://localhost:3000/static/js/bundle.js:11082:20 ) at invokeGuardedCallback ( http://localhost:3000/static/js/bundle.js:11139:35 ) at invokeGuardedCallbackAndCatchFirstError ( http://localhost:3000/static/js/bundle.js:11153:29 ) at executeDispatch ( http://localhost:3000/static/js/bundle.js:15297:7 ) at processDispatchQueueItemsInOrder ( http://localhost:3000/static/js/bundle.js:15323:11 ) at processDispatchQueue ( http://localhost:3000/static/js/bundle.js:15334:9 ) at dispatchEventsForPlugins ( http://localhost:3000/static/js/bundle.js:15343:7 ) at http://localhost:3000/static/js/bundle.js:15503:16 이러한 오류가 발생하였습니다. 아래는 코드입니다. 지난 시간에서 딱히 바꾼게 없는데 오류의 원인을 잘 모르겠어서 질문드립니다. App.js import React, {useState} from "react"; import "./App.css"; import List from "./components/List"; import Form from "./components/Form" export default function App (){ const [todoData, setTodoData] = useState([]); const [value,setValue] = useState(""); const handleSubmit = (e) =>{ e.preventDefault(); // 전송시 페이지 새로고침 방지 함수 let newTodo = { id : Date.now(), title: value, completed : false }; // 새로운 할 일 데이터의 형성 setTodoData(prev => [...prev,newTodo] ) setValue("") // 원래 할 일에 새로운 할 일 데이터의 update 해주는 setState 함수 } const btnStyle = { color: "#fff", border: "none", padding : "5px 9px", borderRadius: "50%", cursor: "pointer", float:"right" } return( <div className="container"> <div className='todoBlock'> <div className="title"> <h1>To do list</h1> </div> <h1 className='text-3xl font-bold underline'>Hello world!</h1> <List todoData= {todoData} setTodoData = {setTodoData}/> <Form handleSubmit = {handleSubmit} value ={value} setValue = {setValue}/> </div> </div> ); } list.js import React from 'react' export default function List({todoData , setTodoData}) { const btnStyle = { color: "#fff", border: "none", padding : "5px 9px", borderRadius: "50%", cursor: "pointer", float:"right" } const handleClick = (id) => { let newTodoData = todoData.filter(data => data.id !== id) console.log('newTodoData',newTodoData); setTodoData(newTodoData); } const getStyle = (completed) => { return { padding : "10px", borderBottom: "1px #ccc solid", textDecoration: completed ? 'line-through' : 'none', } } const handleCompleteChange = (id) => { let newTodoData = todoData.map(data => { if (data.id === id){ data.completed = !data.completed; } return data; }); setTodoData(newTodoData); }; return ( <div> {todoData.map((data)=>( <div style = {getStyle(data.completed)} key = {data.id}> <input type = "checkbox" defaultChecked = {false} onChange = {() => handleCompleteChange(data.id)}/> {data.title} <button style = {btnStyle} onClick = {() => handleClick(data.id)}>X</button> </div> ))} </div> ) } form.js import React from 'react' export default function Form(handleSubmit,value,setValue) { const handleChange = (e) =>{ setValue(e.target.value); } return ( <form style = {{display:"flex"}} onSubmit = {handleSubmit}> <input type = "text" name = "value" style = {{flex: '10', padding :'5px'}} placeholder = "해야 할 일을 입력하세요." value ={value} onChange ={handleChange} /> <input type = "submit" value = "입력" className="btn" style ={{flex:'1'}} /> </form> ) }

  • react
  • redux
  • tdd
  • typescript
  • next.js
이성현 댓글 1 좋아요 0 조회수 662

QueryFailedError: Table 'user' already exists

해결됨

[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스

안녕하세요 선생님 다름이 아니라 synchronize: true, // 동기화 시켜준다 같게 한다. true을 하게되면 동기화를 시켜주는건데 매번 yarn start:dev을할때마다 QueryFailedError: Table '***' already exists 이러한 오류가 나옵니다. 그럼 실행 할때마다 데이터베이스 테이블을 매번 지워야 하는건가요??

  • javascript
  • node.js
  • express
  • docker
  • tdd
  • rest-api
  • nestjs
뽕리뽕뽕 댓글 1 좋아요 0 조회수 753

완강 후 질문이 있습니다~!

미해결

Java/Spring 테스트를 추가하고 싶은 개발자들의 오답노트

안녕하세요 재밌고 알찬 강의 제공해 주셔서 감사합니다. jpa 와 같이 findById 같은 기본적으로 제공해주는 메서드는 따로 테스트를 안해봐도 될거 같은데.. queryDsl 식으로 커스텀한 쿼리를 호출할때 테스트 방법은 어떻게 해야할지 궁금합니다.. h2 와 같은 임베디드디비로 쿼리 조건과 데이터가 잘 나오는지 테스트도 짜고, 다른 인터페이스를 상속받은 구현체의 메서드에서 메모리를 사용해 stream 과 filter 식으로 데이터를 반환하는 구현체를 테스트로 다시 넣어야하는지.. h2로 테스트코드를 짜고, 확인 후, 해당 테스트 코드는 지워버려야 하는지.. 강사님은 어떻게 하고 있는지 궁금합니다.. 감사합니다.

  • spring
  • tdd
  • jpa
  • 소프트웨어-테스트
  • unittest
코스모스 댓글 3 좋아요 2 조회수 737

higher order function 에서

미해결

실리콘밸리 엔지니어가 가르치는 파이썬 기초부터 고급까지

128줄에 return inside에서 inside()를 안하는 이유가 궁금합니다 @higher_order_example 자체가 inside 리턴받은 함수를 자동으로 ()붙여서 실행해주는 것인가요? 136줄에 sample_example()을 안쓰면 121줄에 있는 func 매개변수로 못넣는것인가요???

  • python
  • 알고리즘
남기정 댓글 2 좋아요 1 조회수 368

swaggerui에서 execute했는데 console에서는 계속 typeerror로 n.get함수가 없다는 에러가 발생합니다.

해결됨

[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스

javascript문서를 확인했을때는 배열을 객체로쓴다던가 함수를 부를수없는곳에 작성했다는등의 오류라고 나와있는데 아무리 찾아봐도 그오류가 어디에서 나오는지 왜나오는지를 알수없어서 질문올립니다. // index.js import express from "express"; import { options, dataCoffee, dataUsers } from "./swagger/config.js"; import cors from "cors"; const app = express(); import swaggerUi from "swagger-ui-express"; import swaggerJSDoc from "swagger-jsdoc"; app.use(express.json()); const swaggerSpec = swaggerJSDoc(options); app.use(cors()); app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec)); app.get("/users", (req, res) => { res.send(dataUsers); }); app.get("/starbucks", function (req, res) { res.send(dataCoffee); }); app.listen(3001); // config.js export const options = { definition: { openapi: "3.0.0", info: { title: "swagger-test", version: "1.0.0", }, }, apis: ["./swagger/*-swagger.js"], // files containing annotations as above }; export const dataCoffee = [ { name: "아메리카노", kcal: 5 }, { name: "카푸치노", kcal: 125 }, { name: "헤이즐넛", kcal: 85 }, { name: "카라멜마키아또", kcal: 225 }, { name: "휘핑크림추가", kcal: 115 }, { name: "아메리카노", kcal: 5 }, { name: "아메리카노", kcal: 5 }, { name: "아메리카노", kcal: 5 }, { name: "아메리카노", kcal: 5 }, { name: "아메리카노", kcal: 5 }, { name: "아메리카노", kcal: 5 }, { name: "아메리카노", kcal: 5 }, { name: "아메리카노", kcal: 5 }, { name: "아메리카노", kcal: 5 }, ]; export const dataUsers = [ { email: "aaa@gmail.com", name: "짱구", phone: "010-2293-3333", personal: "222012-2210392", prefer: "https://google.com", }, { email: "aaa@gmail.com", name: "짱구2", phone: "010-2293-3333", personal: "222012-2210392", prefer: "https://google.com", }, { email: "aaa@gmail.com", name: "짱구3", phone: "010-2293-3333", personal: "222012-2210392", prefer: "https://google.com", }, { email: "aaa@gmail.com", name: "짱구4", phone: "010-2293-3333", personal: "222012-2210392", prefer: "https://google.com", }, { email: "aaa@gmail.com", name: "짱구5", phone: "010-2293-3333", personal: "222012-2210392", prefer: "https://google.com", }, { email: "aaa@gmail.com", name: "짱구6", phone: "010-2293-3333", personal: "222012-2210392", prefer: "https://google.com", }, ]; // all-swagger.js /** * @swagger * /starbucks: * get: * summary: 커피 * tags: [Coffee] * parameters: * name: String * kcal: int * responses: * 200: * description: 성공 * content: * application/json: * schema: * type: array * items: * properties: * name: * type: String * example: 아메리카노 * kcal: * type: int * example: 5 */ /** * @swagger * /users: * get: * summary: 유저검색 * tags: [Users] * parameters: * name: String * kcal: int * responses: * 200: * description: 성공 * content: * application/json: * schema: * type: array * items: * properties: * name: * type: String * example: 아메리카노 * kcal: * type: int * example: 5 */

  • javascript
  • node.js
  • express
  • docker
  • tdd
  • rest-api
  • nestjs
jay kang 댓글 2 좋아요 0 조회수 575

[세션30] fetchUser시 UseGuard 401에러

해결됨

[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스

안녕하세요, jwt토큰을 입력하여 사용자 인가를 받고 싶은데 그 과정에서 계속 오류가 나서 문의드립니다. 제가 확인하기로는 코드도 정확히 입력하고, HTTP HEADERS로 보내주는 토큰도 문제 없어서요. 에러 강의에서 jwt를 넣어주지 않았을 때 발생한다는 에러가 발생합니다. 제가 보기에는 토큰값이 잘못된것 같은데, login으로 받아온 토큰을 바로 넣는거라 만료가 되지도 않았을텐데 해결이 안되네요. 제 코드는 아래와 같습니다. users.resolver.ts // users.resolver.ts import { Args, Int, Mutation, Query, Resolver } from '@nestjs/graphql'; import { User } from './entities/user.entity'; import { UsersService } from './users.service'; import * as bcrypt from 'bcrypt'; import { UseGuards } from '@nestjs/common'; import { GqlAuthAccessGuard } from '../auth/guards/gql-auth.guard'; // import { AuthGuard } from '@nestjs/passport'; // 추가 @Resolver() export class UsersResolver { constructor( private readonly usersService: UsersService, // ) {} @UseGuards(GqlAuthAccessGuard) // 수정 @Query(() => String) fetchUser(): string { console.log('인가에 성공하였습니다'); return '인가에 성공하였습니다.'; } @Mutation(() => User) async createUser( @Args('email') email: string, @Args('password') password: string, @Args('name') name: string, @Args({ name: 'age', type: () => Int }) age: number, ): Promise<User> { // const hashedPassword = await bcrypt.hash(password, 10); // return this.usersService.create({ email, hashedPassword, name, age }); // } return this.usersService.create({ email, password, name, age }); } } gql-auth.guard.ts import { ExecutionContext } from '@nestjs/common'; import { GqlExecutionContext } from '@nestjs/graphql'; import { AuthGuard } from '@nestjs/passport'; export class GqlAuthAccessGuard extends AuthGuard('access') { getRequest(context: ExecutionContext) { const gqlContext = GqlExecutionContext.create(context); return gqlContext.getContext().req; } } jwt-access.strategy.ts import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; export class JwtAccessStrategy extends PassportStrategy(Strategy, 'access') { constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: '나의비밀번호', }); } validate(payload) { console.log('페이로드', payload); return { id: payload.sub, }; } } auth.module.ts import { Module } from '@nestjs/common'; import { AuthResolver } from './auth.resolver'; import { AuthService } from './auth.service'; import { UsersModule } from '../users/users.module'; import { JwtModule } from '@nestjs/jwt'; import { JwtAccessStrategy } from './strategy/jwt-access.strategy'; @Module({ imports: [ JwtModule.register({}), UsersModule, // 서비스를 각각 불러오기보다는 module을 통으로 불러오는게 낫다. 원래는 import 에 TypeOrmModule.forFeature([Users])& providers에 UsersServie가 있었음. ], providers: [ JwtAccessStrategy, AuthResolver, // AuthService, // ], }) export class AuthModule {}

  • javascript
  • node.js
  • express
  • docker
  • tdd
  • rest-api
  • nestjs
yskim 댓글 1 좋아요 0 조회수 320

self.client.post에 글이 생성되지않습니다

미해결

Do It! 장고+부트스트랩: 파이썬 웹개발의 정석

강의 영상과 똑같이 작성했음에도 last_post의 내용이 client가 생성한 post가 아닌, post_003의 내용이 들어가면서 Failed가 발생합니다. 실행결과 Failed self.assertEqual(last_post.title, 'Post Form 만들기') AssertionError: '세 번째 포스트 입니다.' != 'Post Form 만들기' - 세 번째 포스트 입니다. + Post Form 만들기 [test.py 코드] from time import sleep from django.test import TestCase, Client from bs4 import BeautifulSoup from .models import Post, Category, Tag from django.contrib.auth.models import User class TestView(TestCase): def setUp(self): self.client = Client() # 사용자 생성 self.user_yunju = User.objects.create_user( username='yunju', password='0129' ) self.user_subin = User.objects.create_user( username='subin', password='cute0313' ) self.user_yunju.is_staff = True self.user_yunju.save() # 카테고리 생성 self.category_programming = Category.objects.create( name='programming', slug='programming' ) self.category_music = Category.objects.create( name='music', slug='music' ) # 태그 생성 self.tag_python_kar = Tag.objects.create( name="파이썬 공부", slug='파이썬-공부' ) self.tag_python = Tag.objects.create( name="python", slug='python' ) self.tag_django = Tag.objects.create( name="django", slug='django' ) # 포스트 생성 self.post_001 = Post.objects.create( title="첫 번째 포스트 입니다.", content="Hello World! We are the World", author=self.user_yunju, category=self.category_programming ) self.post_001.tags.add(self.tag_django) self.post_002 = Post.objects.create( title="두 번째 포스트 입니다.", content="저는 마라탕과 떡볶이를 사랑합니다", author=self.user_subin, category=self.category_music ) self.post_003 = Post.objects.create( title="세 번째 포스트 입니다.", content="Category가 없는 포스트입니다.", author=self.user_subin ) self.post_003.tags.add(self.tag_django) self.post_003.tags.add(self.tag_python) # 내비게이션바 함수 def navbar_test(self, soup): navbar = soup.nav self.assertIn('Blog', navbar.text) self.assertIn('Blog', navbar.text) logo_btn = navbar.find('a', text='Do It Django') self.assertEqual(logo_btn.attrs['href'], '/') home_btn = navbar.find('a', text='Home') self.assertEqual(home_btn.attrs['href'], '/') blog_btn = navbar.find('a', text='Blog') self.assertEqual(blog_btn.attrs['href'], '/blog/') about_me_btn = navbar.find('a', text='About me') self.assertEqual(about_me_btn.attrs['href'], '/about_me/') # 카테고리 카드 함수 def category_card_test(self, soup): categories_card = soup.find('div', id='categories-card') self.assertIn('Categories', categories_card.text) self.assertIn( f'{self.category_programming}({self.category_programming.post_set.count()})', categories_card.text ) self.assertIn( f'{self.category_music}({self.category_music.post_set.count()})', categories_card.text ) self.assertIn( f'미분류({Post.objects.filter(category=None).count()})', categories_card.text ) # 포스트가 있는 경우 def test_post_list_with_posts(self): self.assertEqual(Post.objects.count(), 3) response = self.client.get('/blog/') self.assertEqual(response.status_code, 200) soup = BeautifulSoup(response.content, 'html.parser') self.assertIn('Blog', soup.title.text) self.navbar_test(soup) self.category_card_test(soup) main_area = soup.find('div', id='main-area') post_001_card = main_area.find('div', id='post-1') self.assertIn(self.post_001.title, post_001_card.text) self.assertIn(self.post_001.category.name, post_001_card.text) self.assertIn(self.tag_django.name, post_001_card.text) self.assertNotIn(self.tag_python.name, post_001_card.text) self.assertNotIn(self.tag_python_kar.name, post_001_card.text) post_002_card = main_area.find('div', id='post-2') self.assertIn(self.post_002.title, post_002_card.text) self.assertIn(self.post_002.category.name, post_002_card.text) self.assertNotIn(self.tag_django.name, post_002_card.text) self.assertNotIn(self.tag_python.name, post_002_card.text) self.assertNotIn(self.tag_python_kar.name, post_002_card.text) post_003_card = main_area.find('div', id='post-3') self.assertIn(self.post_003.title, post_003_card.text) self.assertIn('미분류', post_003_card.text) self.assertIn(self.tag_django.name, post_003_card.text) self.assertIn(self.tag_python.name, post_003_card.text) self.assertNotIn(self.tag_python_kar.name, post_003_card.text) self.assertIn(self.post_001.author.username.upper(), main_area.text) self.assertIn(self.post_002.author.username.upper(), main_area.text) # 포스트가 없는 경우 def test_post_list_without_posts(self): Post.objects.all().delete() self.assertEqual(Post.objects.count(), 0) response = self.client.get('/blog/') self.assertEqual(response.status_code, 200) soup = BeautifulSoup(response.content, 'html.parser') self.navbar_test(soup) self.assertIn('Blog', soup.title.text) main_area = soup.find('div', id='main-area') self.assertIn('아직 게시물이 없습니다.', main_area.text) # 상세페이지 함수 def test_post_detail(self): self.assertEqual(Post.objects.count(), 3) self.assertEqual(self.post_001.get_absolute_url(), '/blog/1/') response = self.client.get(self.post_001.get_absolute_url()) self.assertEqual(response.status_code, 200) soup = BeautifulSoup(response.content, 'html.parser') self.navbar_test(soup) self.category_card_test(soup) self.assertIn(self.post_001.title, soup.title.text) main_area = soup.find('div', id='main-area') post_area = main_area.find('div', id='post-area') self.assertIn(self.post_001.title, post_area.text) self.assertIn(self.post_001.category.name, post_area.text) self.assertIn(self.user_yunju.username.upper(), post_area.text) self.assertIn(self.post_001.content, post_area.text) self.assertIn(self.tag_django.name, post_area.text) self.assertNotIn(self.tag_python.name, post_area.text) self.assertNotIn(self.tag_python_kar.name, post_area.text) # 카테고리별 페이지 나타내는 함수 def test_category_page(self): response = self.client.get( self.category_programming.get_absolute_url()) self.assertEqual(response.status_code, 200) soup = BeautifulSoup(response.content, 'html.parser') self.navbar_test(soup) self.category_card_test(soup) main_area = soup.find('div', id='main-area') self.assertIn(self.category_programming.name, main_area.h1.text) self.assertIn(self.category_programming.name, main_area.text) self.assertIn(self.post_001.title, main_area.text) self.assertNotIn(self.post_002.title, main_area.text) self.assertNotIn(self.post_003.title, main_area.text) # 태그 페이지를 나타내는 함수 def test_tag_page(self): response = self.client.get(self.tag_django.get_absolute_url()) self.assertEqual(response.status_code, 200) soup = BeautifulSoup(response.content, 'html.parser') self.navbar_test(soup) self.category_card_test(soup) self.assertIn(self.tag_django.name, soup.h1.text) main_area = soup.find('div', id='main-area') self.assertIn(self.tag_django.name, main_area.text) self.assertIn(self.post_001.title, main_area.text) self.assertNotIn(self.post_002.title, main_area.text) self.assertIn(self.post_003.title, main_area.text) # 로그인하지 않은 사용자에 대한 폼 제한 함수 def test_create_post_without_login(self): response = self.client.get('/blog/create_post/') self.assertNotEqual(response.status_code, 200) # 폼(form)을 이용한 포스트 작성 페이지 생성 # 로그인한 사용자만 폼 작성 가능 def test_create_post_with_login(self): self.client.login(username='yunju', password='0129') response = self.client.get('/blog/create_post/') self.assertEqual(response.status_code, 200) soup = BeautifulSoup(response.content, 'html.parser') self.assertEqual('Create Post - Blog', soup.title.text) main_area = soup.find('div', id='main-area') self.assertIn('Create a New Post', main_area.text) self.client.post( '/blog/create_post/', { 'title': 'Post Form 만들기', 'content': 'Post Form 페이지를 만듭시다.', }, ) last_post = Post.objects.last() self.assertEqual(last_post.title, 'Post Form 만들기') self.assertEqual(last_post.author.username, 'yunju') self.assertEqual(last_post.content, 'Post Form 페이지 만들어보자!') [views.py 코드] from django.core.exceptions import PermissionDenied from django.shortcuts import render, redirect from django.views.generic import ListView, DetailView, CreateView, UpdateView from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .models import Post, Category, Tag # 리스트를 출력하는 django 기본 라이브러리 class PostList(ListView): model = Post ordering = '-pk' def get_context_data(self, **kwargs): context = super(PostList, self).get_context_data() context['categories'] = Category.objects.all() context['no_category_post_count'] = Post.objects.filter( category=None).count() return context # 하나의 리스트를 불러오는 django 기본 라이브러리 class PostDetail(DetailView): model = Post def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data() context['categories'] = Category.objects.all() context['no_category_post_count'] = Post.objects.filter( category=None).count() return context # 포스트 생성 함수 class PostCreate(LoginRequiredMixin, UserPassesTestMixin, CreateView): model = Post fields = ['title', 'hook_text', 'content','head_image', 'file_upload', 'category'] def test_func(self): return self.request.user.is_superuser or self.request.user.is_staff def form_valid(self, form): current_user = self.request.user if current_user.is_authenticated and (current_user.is_staff or current_user.is_superuser): form.instance.author = current_user return super(PostCreate, self).form_valid(form) else: return redirect('/blog/') class PostUpdate(LoginRequiredMixin, UpdateView): model = Post fields = ['title', 'hook_text', 'content','head_image', 'file_upload', 'category'] template_name = 'blog/post_update_form.html' def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated and request.user == self.get_object().author: return super(PostUpdate, self).dispatch(request, *args, **kwargs) else: return PermissionDenied # 카테고리별 페이지 반환 함수 def category_page(request, slug): if slug == 'no_category': category = '미분류' post_list = Post.objects.filter(category=None) else: category = Category.objects.get(slug=slug) post_list = Post.objects.filter(category=category) return render( request, 'blog/post_list.html', { 'post_list': post_list, 'categories': Category.objects.all(), 'no_category_post_count': Post.objects.filter(category=None).count(), 'category': category } ) # 태그별 페이지 반환 함수 def tag_page(request, slug): tag = Tag.objects.get(slug=slug) post_list = tag.post_set.all() return render( request, 'blog/post_list.html', { 'post_list': post_list, 'categories': Category.objects.all(), 'no_category_post_count': Post.objects.filter(category=None).count(), 'tag': tag } )

  • HTML/CSS
  • javascript
  • python
  • django
  • bootstrap
  • aws
  • docker
  • tdd
syrose00 댓글 1 좋아요 0 조회수 356

섹션7 - 테스트 환경의 독립성을 보장하자

미해결

Practical Testing: 실용적인 테스트 가이드

학습 관련 질문을 남겨주세요. 어떤 부분이 고민인지, 무엇이 문제인지 상세히 작성하면 더 좋아요! 먼저 유사한 질문이 있었는지 검색해 보세요. 서로 예의를 지키며 존중하는 문화를 만들어가요. 안녕하세요. 강의 재미나게 잘 보고있습니다. 제목에 남겨드린 강의에서 creatOrderWithNoStock의 주제와 벗어나 given절의 deductQuantity에서 예외가 발생할 수 있는 상황을 예를 들어서 설명해 주셨고, 테스트 환경에서는 가능한 생성자를 기반으로 환경을 구성하여 진행하는것이 좋다고 말씀 주셨는데 그럼 이 경우에는 Stock stock1 = Stock.create("001", 2); Stock stock2 = Stock.create("002", 1); 와 같이 생성 시점에 이미 부족한 수량으로 설정 하여 테스트를 진행하여 deductQuantity를 사용하지 않고, deductQuantity의 경우 따로 단위 테스트를 통해 수량 감소를 확인하는걸로 테스트를 구성하는 식으로 가면 되는건지 궁금합니다.

  • spring
  • tdd
  • jpa
  • mockito
  • 소프트웨어-테스트
  • junit5
댓글 1 좋아요 1 조회수 486

controller, service용 dto를 분리시키는 것에 대한 질문

미해결

Practical Testing: 실용적인 테스트 가이드

항상 잘 듣고 있습니다. 감사합니다. controller layer와 service layer의 dto를 서로 분리시켜서 service layer가 상위 레이어를 모르도록 한다는 것은 이해가 되었습니다. 질문 드리겠습니다! dto를 분리할 때, 중복된 코드가 복잡성을 증가 시킬 수도 있고 운영 시, 두 dto 간의 변환 과정의 비용 이 어느 정도 성능에 영향을 미칠 수 있다고도 생각합니다. 2개로 분리하는 방법은 일반적인 설계 패턴은 아니라고 생각되는데, 혹시 현업에서도 자주 사용하는 방식이신지가 궁금합니다. service에서 생성된 response 데이터에 대해서도 controller만의 response dto 를 따로 생성할 필요가 있는지 궁금합니다. 클라이언트로 내려주는 응답 객체로 controller 클래스에서 ResponseEntity 는 사용하지 않으시는지, 주로 현업에서도 강의에서처럼 응답 객체(ApiReponse)를 커스텀해서 내려주는 방식을 선호하시는지 궁금합니다.

  • spring
  • tdd
  • jpa
  • mockito
  • 소프트웨어-테스트
  • junit5
재영 댓글 3 좋아요 3 조회수 3728

Controller 테스트할 때, Service 에 대한 로직

미해결

Practical Testing: 실용적인 테스트 가이드

안녕하세요! 테스트에 대해 의아했던 부분이 많이 풀리는 강의입니다. 정말 감사드려요. 강의를 잘 듣고 있다가 궁금한게 생겨서요! controller @mockBean Service service @test void postData() { // when when(service.message()).thenRetrun() } 간단하게 코드를 적어봣는데요! service에 대해 MockBean으로 주입만 해줬을 뿐, Service에 대한 로직이 없어서요! 제 생각에는 Service가 return 하는 부분은 이미 서비스 계층에서 테스트가 끝났고 Controller 에 테스트를 해야하는 주점은 1 ) Request 에 오는 데이터들의 검증 뿐이라고 생각하는데 맞나요? Get 같은 경우에도 Service에 오는 건 그냥 빈 배열처리하셨더라구요! 감사합니다!

  • spring
  • tdd
  • jpa
  • mockito
  • 소프트웨어-테스트
  • junit5
이얏 댓글 2 좋아요 0 조회수 690

토이 프로젝트 github 주소 공유 부탁드려요!

미해결

Java/Spring 테스트를 추가하고 싶은 개발자들의 오답노트

따라해보려고 합니다! 토이프로젝트 소스 공유 부탁드려요!

  • spring
  • tdd
  • jpa
  • 소프트웨어-테스트
  • unittest
Minkyu Ha 댓글 1 좋아요 2 조회수 890

영상에서 사용하신 커맨드가 궁금합니다.

미해결

따라하며 배우는 리액트 A-Z[19버전 반영]

섹션 2 할 일 목록 추가하기 영상 3분 4초 부분에서 Ctrl + K + F가 아니라면 어떤 커맨드 사용하신 건지 알 수 있을까요?

  • react
  • redux
  • tdd
  • typescript
  • next.js
  • 소프트웨어-테스트
dcnm19 댓글 1 좋아요 0 조회수 461

선생님 데이터 import가 안돼요 ㅠㅠ

미해결

[개정판] 파이썬 머신러닝 완벽 가이드

- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 강의 내용을 질문할 경우 몇분 몇초의 내용에 대한 것인지 반드시 기재 부탁드립니다. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 선생님 보스턴 가격예측 데이터 임포트가 안돼요 ㅠㅠ

  • python
  • 머신러닝
  • 통계
이호준 댓글 2 좋아요 0 조회수 497

'블랙핑크' 검색 시에만 오류가 뜨는 현상

미해결

[신규 개정판] 이것이 진짜 크롤링이다 - 실전편 (인공지능 수익화)

안녕하세요. 강사님 아래 코드에서 '블랙핑크' 를 검색할 때 Traceback (most recent call last): File "c:\pratice_crolling\심화1_\03_스포츠 뉴스 크롤링.py ", line 52, in <module> print(article_title.text.strip()) ^^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'text' 다음과 같은 오류가 뜹니다 ㅠㅠ CSS 선택자, 오타도 모두 맞게 확인이 되는데 왜 저 검색어만 오류가 뜰까요ㅠㅠ? # -*- coding: euc-kr -*- # 네이버에서 손흥민, 오승환과 같은 스포츠 관련 검색어 크롤링하기 import requests from bs4 import BeautifulSoup import pyautogui import time search = pyautogui.prompt("어떤 것을 검색하시겠어요?") response = requests.get(f"https://search.naver.com/search.naver?sm=tab_hty.top&where=news&query={search}&oquery=%EC%98%B7%EC%9C%BC%ED%99%98&tqi=i74G%2FdprvTossZPeMhCssssssko-058644") html = response.text soup = BeautifulSoup(html, "html.parser") articles = soup.select(".info_group") for article in articles: # '네이버뉴스' 가 있는 기사만 추출한다. (<a> 하이퍼링크가 2개 이상인 경우에 해당) links = article.select("a.info") if len(links) >=2 : url = links[1].attrs['href'] response = requests.get(url, headers={'User-agent':'Mozila/5.0'}) html = response.text soup = BeautifulSoup(html, "html.parser") # 스포츠 기사인 경우 if "sports" in url: article_title = soup.select_one("h4.title") article_body = soup.select_one("#newsEndContents") # 본문 내에 불필요한 내용 제거 p태그와 div태그의 내용은 출력할 필요가 없다. 없애주자. p_tags = article_body.select("p") # 본문에서 p 태그인 것들을 추출 for p_tag in p_tags: p_tag.decompose() div_tags = article_body.select("div") # 본문에서 div 태그인 것들을 추출 for div_tag in div_tags: div_tag.decompose() # 연예 기사인 경우 elif "entertain" in url: article_title = soup.select_one(".end_tit") article_body = soup.select_one("#articeBody") # 일반 뉴스 기사인 경우 else: article_title = soup.select_one("#title_area") article_body = soup.select_one("#dic_area") # 출력문 print("==================================================== 주소 ===========================================================") print(url.strip()) print("==================================================== 제목 ===========================================================") print(article_title.text.strip()) print("==================================================== 본문 ===========================================================") print(article_body.text.strip()) #strip 함수는 앞 뒤의 공백을 제거한다. time.sleep(0.3)

  • python
  • 웹-크롤링
댓글 2 좋아요 0 조회수 325

도메인 객체를 불변으로 만들어야 하는가가 궁금합니다.

미해결

Java/Spring 테스트를 추가하고 싶은 개발자들의 오답노트

Post를 수정한다면 새로 만들어지는 것이 아닌 존재하는 객체를 변경하는게 조금 더 잘 읽힐것 같은데 불변객체로 만드신 이유가 궁금합니다. 혹시 실무에서도 도메인 엔티티에 대해 불변으로 사용하나요?

  • spring
  • tdd
  • jpa
  • 소프트웨어-테스트
  • unittest
정성훈 댓글 2 좋아요 2 조회수 1676

추상클래스 IntegrationTestSupport을 통한 테스트수행 비용단축에 관한 질문

미해결

Practical Testing: 실용적인 테스트 가이드

안녕하세요 강의 테스트 수행도 비용이다. 환경 통합하기 를 듣다가 궁금한 점이 생겨 질문드립니다. 강의에서는 추상클래스 IntegrationTestSupport에 어노테이션 @SpringBootTest을 달아서 통합테스트가 필요한 테스트클래스가 상속하여 스프링컨테이너가 반복 실행되는걸 단축하는게 인상깊었는데요. 원리가 궁금한 점이 있어 질문드립니다. 어떤 원리로 마치 스프링컨테이너가 전파되듯이 상속받은 클래스로 설정한 컨테이너가 작동하는걸까요? 그리고 어떻게 상속받은 클래스가 또 실행될 줄 알고 그 환경(컨테이너)가 어느시점까지 종료되지 않고 지속되고 있는건지 궁금합니다

  • spring
  • tdd
  • jpa
  • mockito
  • 소프트웨어-테스트
  • junit5
fpg123 댓글 2 좋아요 2 조회수 677

팩토리메서드를 지양하고 생성자 혹은 Builder 패턴을 쓰라는 말씀에 관하여

미해결

Practical Testing: 실용적인 테스트 가이드

팩토리메서드를 지양하고 생성자 혹은 Builder 패턴을 쓰라는 말씀에 관한 질문입니다. 강의 테스트 환경의 독립성을 보장하자 에 6분대 가량에서 나온 설명입니다. OrderServiceTest.java 에서 createOrderWithNoStock() 메서드입니다 하나의 로직을 가지고 있는 팩토리메서드 보다는 생성자 혹은 빌더패턴을 이용하여 다른 로직의 개입으로부터 격리하여 테스트 환경의 독립성을 보장하자라는 말씀으로 이해했는데요 하지만 처음 강의를 해주실 때 Builder패턴이 가독성을 방해해서 테스트 코드 안에 팩토리메서드를 만드셨는데요. 이번에는 다시 독립성을 위해 Builder 패턴을 쓰는게 좋다고 하시니 헷갈립니다. 결국 가독성 vs 독립성의 트레이드오프 관계로 이해해야하나요? 아니면 여기서 슬기롭게 풀어나갈 수 있는 방법이 있나요?

  • spring
  • tdd
  • jpa
  • mockito
  • 소프트웨어-테스트
  • junit5
fpg123 댓글 2 좋아요 0 조회수 1424

실무에서 테스트 프레임워크 사용

해결됨

Java/Spring 테스트를 추가하고 싶은 개발자들의 오답노트

안녕하세요! 강의 잘 보고 있는 수강생입니다 강의를 보니 Mockito나 Junit을 전혀 사용하지 않고 전체 테스트를 작성하시는 것을 보고 많은 감명을 받았습니다. 실무에서도 Mockito나 Junit을 전혀 사용하시지 않는지, 사용한다면 어떤 상황에서 사용하시는지 여쭤보고자 글을 남기게 되었습니다. 좋은 하루 보내세요!

  • spring
  • tdd
  • jpa
  • 소프트웨어-테스트
  • unittest
Jm 댓글 2 좋아요 2 조회수 1080

spring batch 통합 테스트시 @Transactional 사용 어려움 질문이욥!!

미해결

Practical Testing: 실용적인 테스트 가이드

학습 관련 질문을 남겨주세요. 어떤 부분이 고민인지, 무엇이 문제인지 상세히 작성하면 더 좋아요! 먼저 유사한 질문이 있었는지 검색해 보세요. 서로 예의를 지키며 존중하는 문화를 만들어가요. 14분쯤에 spring batch 통합 테스트시 여러 트랜잭션 경계가 참여해 @Transactional 사용이 어려워 주로 deleteAllInBatch를 사용해 수동으로 데이터를 지우신다고 말씀해주셨는데.. spring batch를 한번도 개발해보거나 테스트한적도 없어서 '여러 트랜잭션 경계가 참여하는 상황'에 대해서 잘 떠오르지가 않아서 혹시 간단하게라도 예시 부탁드려도 될까욥?! ㅠㅠ 감사합니다. ※ 평소에 막연히 '테스트 코드 짜봐야지~' 라고 생각만 했던걸 강사님 강의를 듣고난 이후로 테스트 코드 작성을 실천하고 있습니다!! 다른 강의들도 많이많이 찍어주세요!!(3개월에 한번..)

  • spring
  • tdd
  • jpa
  • mockito
  • 소프트웨어-테스트
  • junit5
김우철 댓글 2 좋아요 1 조회수 730

인기 태그

인프런 TOP Writers

주간 인기글