request, err := http.NewRequest("GET", path, nil)
response := httptest.NewRecorder()
r.ServeHTTP(response, request)
var raw map[string]map[string]string
_ = json.Unmarshal(response.Body.Bytes(), &raw)
details := raw["response"]
我有一个TestFunction,正在其中使用此代码。是代码 测试REST API的GET请求。
在我的第一个测试用例中,我命中了一个已定义的处理程序,而在第二个测试用例中,我中了一些随机的处理程序,以使该例失败。
代码通过了,但是每次第二个测试用例给出500作为响应时。
下面是我的测试用例的代码。
func TestGetProviders(t *testing.T) {
type args struct {
path string
handler gin.HandlerFunc
}
tests := []struct {
name string
args args
want bool
}{
{
"First",
args{
"/api/v1/providers",
GetProviders,
},
true,
},
{
"Second",
args{
"/demo",
TheFunc,
},
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
value := copyCodeGet(tt.args.path, tt.args.handler)
if len(value["response"]) > 0 {
statusCode, _ := strconv.Atoi(value["response"]["code"])
if val := statusCode == config.SuccessCode && value["response"]["message"] == config.SuccessMsg; val != tt.want {
t.Errorf("Error is:%v && Status code should be %v, was %d.", value, http.StatusOK, statusCode)
}
}
})
}
}
答案 0 :(得分:1)
最后与
讨论之后mkopriva
我能够解决问题。
我一直在
内的GetErrResponseList中使用Defer c.Request.Body.Close()。import React from 'react'
import { AppState, AppRegistry, View, BackAndroid, Alert, Platform, PushNotificationIOS } from 'react-native'
import { Provider } from 'mobx-react/native'
import StatusBar from 'StatusBar'
import SplashScreen from 'react-native-splash-screen'
import initializeStores, { authStore, accountStore, newsStore, lessonsStore, paymentStore, pushStore } from './src/Stores'
import Router from './src/Router'
import PushNotification from 'react-native-push-notification'
import DeviceInfo from 'react-native-device-info'
import api from './src/utils/api'
/***************************************
<SETUP PUSH NOTIFICATIONS>
**************************************/
const getDeviceModelSync = () => {}
const isPushEnabled = async () => {}
const onRegister = async ({ token }) => {}
if(Platform.OS === 'ios') {
PushNotificationIOS.addEventListener('registrationError', async (error) => {
console.warn('PushNotification registration error: ', error)
try {
// On simulators `registrationError` called each time when permissions requested
const pushRegisterHadFailed = await AsyncStorage.getItem('pushRegisterHadFailed').catch(() => null)
if(!pushRegisterHadFailed) {
await api('POST', '/devices', {}, {
device: {
platform: Platform.OS,
name: getDeviceModelSync(),
is_push_enabled: false,
},
})
await AsyncStorage.setItem('pushRegisterHadFailed', 'true')
}
} catch (e) {
console.warn('Can\'t POST device info to API:', e)
}
})
}
/***************************************
</SETUP PUSH NOTIFICATIONS>
**************************************/
const appStateListener = (state) => {
if (state === 'active') {
AppState.removeEventListener('change', appStateListener);
PushNotification.popInitialNotification(notification => notification && onNotification(notification));
}
};
export default class app extends React.Component {
state = {
initialized: false,
}
handleNotification(notification)
{
console.log('handleNotification');
}
componentDidMount() {
initializeStores()
.then(() => new Promise((resolve) => {
this.setState({
initialized: true,
}, resolve)
}))
.then(() => {
SplashScreen.hide()
})
AppState.addEventListener('change', appStateListener);
var that = this;
PushNotification.configure({
onRegister,
onNotification(notification) {
console.log('onNotification')
console.log( notification );
that.handleNotification(notification);
},
senderID: '#########',
permissions: {
alert: true,
badge: true,
sound: true,
},
popInitialNotification: true,
requestPermissions: false,
})
}
render() {
const initialRouteStack = []
let initialRoute = { name: accountStore.onboardingViewed ? 'authPhone' : 'onboarding' }
if(authStore.token) {
if(accountStore.isParent) {
initialRoute = { name: 'children' }
} else {
initialRoute = { name: 'home' }
}
} else if(authStore.loginPhone) {
// Push authPhone scene in histiry as previous one
initialRouteStack.push({ name: 'authPhone' })
initialRoute = { name: 'authCode' }
}
initialRouteStack.push(initialRoute)
return (
<View style={{ flex: 1 }}>
<StatusBar barStyle="light-content" />
{
this.state.initialized ? (
<Provider
account={accountStore}
auth={authStore}
news={newsStore}
lessons={lessonsStore}
payment={paymentStore}
pushes={pushStore}
initializeStores={initializeStores}
>
<Router
initialRoute={initialRoute}
initialRouteStack={initialRouteStack} />
</Provider>
) : (
null
)
}
</View>
)
}
}
AppRegistry.registerComponent('app', () => app)
喜欢
import React from 'react'
import { View, Modal, Platform } from 'react-native'
import { Navigator } from 'react-native-deprecated-custom-components'
import Navbar from './Components/Navbar'
import AppBackground from './Components/AppBackground'
import ActivityLoadingScreen from './ActivityLoadingScreen'
import AuthPhoneScreen from './AuthPhoneScreen'
import AuthCodeScreen from './AuthCodeScreen'
import AuthAccountMissingScreen from './AuthAccountMissingScreen'
import ChildrenScreen from './ChildrenScreen'
import HomeScreen from './HomeScreen'
import OnboardingScreen from './OnboardingScreen'
import UserScreen from './UserScreen'
import TimetableScreen from './TimetableScreen'
import PaymentScreen from './PaymentScreen'
import PushScreen from './PushScreen'
export const routes = {
authPhone: AuthPhoneScreen,
authCode: AuthCodeScreen,
authAccountMissing: AuthAccountMissingScreen,
home: HomeScreen,
onboarding: OnboardingScreen,
user: UserScreen,
timetable: TimetableScreen,
children: ChildrenScreen,
payment: PaymentScreen,
pushlist: PushScreen,
}
export default class Router extends React.Component {
state = {
activityLoading: false,
}
_navigator = null
_routeHandler = null
activityLoading = {
show: () => {
this.setState({
activityLoading: true,
})
},
abort: () => new Promise((resolve) => {
this.setState({
activityLoading: false,
// Workaround due Modal and Alert dead-locks
// https://github.com/facebook/react-native/issues/10471
}, () => {
if(Platform.OS === 'ios') {
setTimeout(resolve, 1200)
} else {
resolve()
}
})
}),
replaceWith: (route, force) => new Promise((resolve) => {
const method = force ? 'resetTo' : 'push'
this.setState(
{ activityLoading: false },
// Delay route transition until modal are closing
() => setTimeout(() => {
this._navigator[method](route)
resolve()
}, 400),
)
}),
}
renderScene = (route, navigator) => {
const { name, ...routeParams } = route,
RouteHandler = routes[name]
return (
<AppBackground>
<RouteHandler
ref={routeHandler => navigator._routeHandler = routeHandler}
navigator={navigator}
activityLoading={this.activityLoading}
{...this.props}
{...routeParams} />
</AppBackground>
)
}
configureScene(route) {
const { configureScene } = routes[route.name].navbar || {}
if(configureScene) {
return configureScene(route) || Navigator.SceneConfigs.PushFromRight
}
return Navigator.SceneConfigs.PushFromRight
}
render() {
const {
initialRoute = { name: 'authPhone' },
initialRouteStack = null,
} = this.props
return (
<View style={{ flex: 1 }}>
<Modal
animationType="fade"
transparent
visible={this.state.activityLoading}
onRequestClose={() => {}}
>
<AppBackground style={{ opacity: 0.7 }} />
<ActivityLoadingScreen />
</Modal>
<Navigator
ref={navigator => this._navigator = navigator}
style={{ flex: 1 }}
initialRoute={initialRoute}
initialRouteStack={initialRouteStack}
renderScene={this.renderScene}
configureScene={this.configureScene}
navigationBar={
<Navbar />
} />
</View>
)
}
}
引起问题的原因不需要在处理程序中关闭作为请求主体的问题。因此它刚好在使用前就关闭了机体,因此将其卸下解决了问题。