package wopi import ( "errors" "github.com/cloudreve/Cloudreve/v3/pkg/cache" "github.com/cloudreve/Cloudreve/v3/pkg/mocks/requestmock" "github.com/cloudreve/Cloudreve/v3/pkg/request" "github.com/stretchr/testify/assert" testMock "github.com/stretchr/testify/mock" "io" "net/http" "net/url" "strings" "testing" ) func TestClient_AvailableExts(t *testing.T) { a := assert.New(t) endpoint, _ := url.Parse("http://localhost:8001/hosting/discovery") client := &client{ cache: cache.NewMemoStore(), config: config{ discoveryEndpoint: endpoint, }, } // Discovery failed { expectedErr := errors.New("error") mockHttp := &requestmock.RequestMock{} client.http = mockHttp mockHttp.On( "Request", "GET", endpoint.String(), testMock.Anything, testMock.Anything, ).Return(&request.Response{ Err: expectedErr, }) res := client.AvailableExts() a.Empty(res) mockHttp.AssertExpectations(t) } // pass { client.discovery = &WopiDiscovery{} client.actions = map[string]map[string]Action{ ".doc": { string(ActionPreviewFallback): Action{}, }, ".ppt": {}, ".xls": { "not_supported": Action{}, }, } res := client.AvailableExts() a.Len(res, 1) a.Equal("doc", res[0]) } } func TestClient_RefreshDiscovery(t *testing.T) { a := assert.New(t) endpoint, _ := url.Parse("http://localhost:8001/hosting/discovery") client := &client{ cache: cache.NewMemoStore(), config: config{ discoveryEndpoint: endpoint, }, } // cache hit { client.cache.Set(DiscoverResponseCacheKey, WopiDiscovery{Text: "test"}, 0) a.NoError(client.checkDiscovery()) a.Equal("test", client.discovery.Text) client.discovery = &WopiDiscovery{} client.cache.Delete([]string{DiscoverResponseCacheKey}, "") } // malformed xml { mockHttp := &requestmock.RequestMock{} client.http = mockHttp mockHttp.On( "Request", "GET", endpoint.String(), testMock.Anything, testMock.Anything, ).Return(&request.Response{ Response: &http.Response{ StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"code":203}`)), }, }) res := client.refreshDiscovery() a.ErrorContains(res, "failed to parse") mockHttp.AssertExpectations(t) } // all pass { testResponse := ` ` mockHttp := &requestmock.RequestMock{} client.http = mockHttp mockHttp.On( "Request", "GET", endpoint.String(), testMock.Anything, testMock.Anything, ).Return(&request.Response{ Response: &http.Response{ StatusCode: 200, Body: io.NopCloser(strings.NewReader(testResponse)), }, }) res := client.refreshDiscovery() a.NoError(res, res) a.NotEmpty(client.actions[".docx"]) a.NotEmpty(client.actions[".docx"][string(ActionPreview)]) a.NotEmpty(client.actions[".docx"][string(ActionEdit)]) mockHttp.AssertExpectations(t) } }