Skip to content

Commit

Permalink
[refactor] Create -> create, Parse -> parse
Browse files Browse the repository at this point in the history
  • Loading branch information
haf committed May 6, 2016
1 parent 68c4423 commit d0e5b0b
Show file tree
Hide file tree
Showing 7 changed files with 25 additions and 90 deletions.
1 change: 1 addition & 0 deletions HttpFs.IntegrationTests/HttpFs.IntegrationTests.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
<WarningsAsErrors>
</WarningsAsErrors>
<DocumentationFile>bin\Debug\HttpFs.IntegrationTests.xml</DocumentationFile>
<Externalconsole>true</Externalconsole>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
Expand Down
11 changes: 5 additions & 6 deletions HttpFs.IntegrationTests/NancyFxTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ type ``Integration tests`` ()=
|> Request.setHeader (Authorization "QWxhZGRpbjpvcGVuIHNlc2FtZQ==" )
|> Request.setHeader (Connection "conn1" )
|> Request.setHeader (ContentMD5 "Q2hlY2sgSW50ZWdyaXR5IQ==" )
|> Request.setHeader (ContentType (ContentType.Create("application", "json")))
|> Request.setHeader (ContentType (ContentType.create("application", "json")))
|> Request.setHeader (Date (new DateTime(1999, 12, 31, 11, 59, 59, DateTimeKind.Utc)))
|> Request.setHeader (From "[email protected]" )
|> Request.setHeader (IfMatch "737060cd8c284d8af7ad3082f209582d" )
Expand Down Expand Up @@ -306,15 +306,14 @@ type ``Integration tests`` ()=
response |> should equal expected

[<Test>]
member x.``throws ArgumentException for invalid Content-Type charset when reading string`` () =
member x.``assumes utf8 encoding for invalid Content-Type charset when reading string`` () =
try
Request.create Get (uriFor "/MoonLanguageInvalidEncoding")
|> Request.responseAsString
|> run
|> ignore
Assert.Fail "should throw ArgumentException"
with :? ArgumentException as e ->
()
Assert.Fail "should default to utf8"

// .Net encoder doesn't like utf8, seems to need utf-8
[<Test>]
Expand Down Expand Up @@ -480,8 +479,8 @@ type ``Integration tests`` ()=
[<Test>]
member x.``returns the uploaded file names`` () =
let firstCt, secondCt =
ContentType.Parse "text/plain" |> Option.get,
ContentType.Parse "text/plain" |> Option.get
ContentType.parse "text/plain" |> Option.get,
ContentType.parse "text/plain" |> Option.get

let req =
Request.create Post (uriFor "/filenames")
Expand Down
10 changes: 5 additions & 5 deletions HttpFs.IntegrationTests/SuaveTests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ open Suave.Successful
open Suave.RequestErrors
open Suave.Operators
open Suave.Web

open HttpFs // Async.AwaitTask overload
open HttpFs.Client // The client itself

Expand Down Expand Up @@ -54,6 +53,7 @@ type ``Suave Integration Tests`` () =
logger = Logging.Loggers.saneDefaultsFor Suave.Logging.LogLevel.Warn }
let listening, server = startWebServerAsync config app
Async.Start(server, cts.Token) |> ignore
Async.RunSynchronously listening |> ignore
()

[<TestFixtureTearDown>]
Expand All @@ -63,10 +63,10 @@ type ``Suave Integration Tests`` () =
[<Test>]
member x.``server receives valid filenames``() =
let firstCt, secondCt, thirdCt, fourthCt =
ContentType.Parse "text/plain" |> Option.get,
ContentType.Parse "text/plain" |> Option.get,
ContentType.Create("application", "octet-stream"),
ContentType.Create("image", "gif")
ContentType.parse "text/plain" |> Option.get,
ContentType.parse "text/plain" |> Option.get,
ContentType.create("application", "octet-stream"),
ContentType.create("image", "gif")

let req =
postTo "filenames"
Expand Down
12 changes: 6 additions & 6 deletions HttpFs.UnitTests/RequestBody.fs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ let apiUsage =
[<Tests>]
let contentType =
testCase "can convert to string" <| fun _ ->
let subject = ContentType.Create("application", "multipart", charset=Encoding.UTF8, boundary="---apa")
let subject = ContentType.create("application", "multipart", charset=Encoding.UTF8, boundary="---apa")
Assert.Equal(subject.ToString(), "application/multipart; charset=utf-8; boundary=---apa")

[<Tests>]
Expand Down Expand Up @@ -63,7 +63,7 @@ let bodyFormatting =
let clientState = { HttpFsState.empty with random = Random testSeed }

let fileCt, fileContents =
ContentType.Parse "text/plain" |> Option.get,
ContentType.parse "text/plain" |> Option.get,
"Hello World"

let form =
Expand Down Expand Up @@ -95,7 +95,7 @@ let bodyFormatting =

Assert.Equal("should have correct body", expected, subject)
Assert.Equal("should have new ct",
ContentType.Create("multipart", "form-data", boundary=expectedBoundary),
ContentType.create("multipart", "form-data", boundary=expectedBoundary),
newCt |> Option.get)

testCase "multipart/form-data with multipart/mixed" <| fun _ ->
Expand All @@ -104,8 +104,8 @@ let bodyFormatting =
let clientState = { HttpFsState.empty with random = Random testSeed }

let firstCt, secondCt, fileContents =
ContentType.Parse "text/plain" |> Option.get,
ContentType.Parse "text/plain" |> Option.get,
ContentType.parse "text/plain" |> Option.get,
ContentType.parse "text/plain" |> Option.get,
"Hello World"

let form =
Expand Down Expand Up @@ -178,7 +178,7 @@ let bodyFormatting =
let bodyToString = body |> bodyToBytes |> utf8.GetString
Assert.Equal(bodyToString, "submit=Join+Now!&user_name=%c3%85sa+den+R%c3%b6de&user_pass=Bovi%c4%87")
Assert.Equal("should have new ct",
ContentType.Parse "application/x-www-form-urlencoded",
ContentType.parse "application/x-www-form-urlencoded",
newCt)
]

Expand Down
2 changes: 1 addition & 1 deletion HttpFs.UnitTests/SendingStreams.fs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ let tests =
let ctx = runWithConfig app
try
use fs = File.OpenRead (pathOf "pix.gif")
let file = "pix.gif", ContentType.Create("image", "gif"), StreamData fs
let file = "pix.gif", ContentType.create("image", "gif"), StreamData fs

use ms = new MemoryStream()
//printfn "--- get response"
Expand Down
77 changes: 6 additions & 71 deletions HttpFs/HttpFs.fs
Original file line number Diff line number Diff line change
Expand Up @@ -13,60 +13,7 @@ open Hopac

[<AutoOpen>]
module internal Prelude =

open System
open System.IO
open System.Threading.Tasks
open System.Threading

let flip f a b = f b a

type Microsoft.FSharp.Control.Async with
/// Raise an exception on the async computation/workflow.
static member AsyncRaise (e : exn) =
Async.FromContinuations(fun (_,econt,_) -> econt e)

/// Await a task asynchronously
static member AwaitTask (t : Task) =
let flattenExns (e : AggregateException) = e.Flatten().InnerExceptions.[0]
let rewrapAsyncExn (it : Async<unit>) =
async { try do! it with :? AggregateException as ae -> do! Async.AsyncRaise (flattenExns ae) }
let tcs = new TaskCompletionSource<unit>(TaskCreationOptions.None)
t.ContinueWith((fun t' ->
if t.IsFaulted then tcs.SetException(t.Exception |> flattenExns)
elif t.IsCanceled then tcs.SetCanceled ()
else tcs.SetResult(())), TaskContinuationOptions.ExecuteSynchronously)
|> ignore
tcs.Task |> Async.AwaitTask |> rewrapAsyncExn

static member map f value =
async {
let! v = value
return f v
}

static member bind f value =
async {
let! v = value
return! f v
}

type Microsoft.FSharp.Control.AsyncBuilder with

/// An extension method that overloads the standard 'Bind' of the 'async' builder. The new overload awaits on
/// a standard .NET task
member x.Bind(t : Task<'T>, f:'T -> Async<'R>) : Async<'R> = async.Bind(Async.AwaitTask t, f)

/// An extension method that overloads the standard 'Bind' of the 'async' builder. The new overload awaits on
/// a standard .NET task which does not commpute a value
member x.Bind(t : Task, f : unit -> Async<'R>) : Async<'R> = async.Bind(Async.AwaitTask t, f)

module String =
let toLowerInvariant (s : string) =
s.ToLowerInvariant()

let toLower (s : string) =
s.ToLower()

module Option =
let orDefault def =
Expand All @@ -78,19 +25,6 @@ module internal Prelude =
let bytes (s : string) =
Encoding.ASCII.GetBytes s

module UTF8 =
open System
open System.Text

let bytes (s : string) =
Encoding.UTF8.GetBytes s

module Map =
let put k v m =
match m |> Map.tryFind k with
| Some _ -> m |> Map.remove k |> Map.add k v
| None -> m |> Map.add k v

module Logging =

/// The log levels specify the severity of the message.
Expand Down Expand Up @@ -347,14 +281,14 @@ module Client =
397 * hash x.typ
^^^ hash x.subtype

static member Create(typ : string, subtype : string, ?charset : Encoding, ?boundary : string) =
static member create(typ : string, subtype : string, ?charset : Encoding, ?boundary : string) =
{ typ = typ
subtype = subtype
charset = charset
boundary = boundary }

// TODO, use: https://github.com/freya-fs/freya/blob/master/src/Freya.Types.Http/Types.fs#L420-L426
static member Parse (str : string) =
static member parse (str : string) =
match str.Split [| '/' |], str.IndexOf(';') with
| [| typ; subtype |], -1 ->
Some { typ = typ; subtype = subtype; charset = None; boundary = None }
Expand Down Expand Up @@ -849,11 +783,11 @@ module Client =
formData |> List.forall (function | NameValue _ -> true | _ -> false)

if onlyNameValues then
ContentType.Parse "application/x-www-form-urlencoded",
ContentType.parse "application/x-www-form-urlencoded",
formatBodyUrlencoded encoding formData
else
let boundary = generateBoundary clientState
ContentType.Create("multipart", "form-data", boundary=boundary) |> Some,
ContentType.create("multipart", "form-data", boundary=boundary) |> Some,
generateFormData clientState encoding boundary formData

open Impl
Expand Down Expand Up @@ -1118,7 +1052,8 @@ module Client =
| null | "" ->
ISOLatin1 // TODO: change to UTF-8
| responseCharset ->
Encoding.GetEncoding(mapEncoding responseCharset)
try Encoding.GetEncoding(mapEncoding responseCharset)
with _ -> Encoding.UTF8

| Some enc ->
enc
Expand Down
2 changes: 1 addition & 1 deletion Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ task :restore => :paket_bootstrap do
end

task :yolo do
system %{ruby -pi.bak -e "gsub(/module internal YoLo/, 'module internal Fakta.YoLo')" paket-files/haf/YoLo/YoLo.fs} \
system %{ruby -pi.bak -e "gsub(/module internal YoLo/, 'module internal HttpFs.YoLo')" paket-files/haf/YoLo/YoLo.fs} \
unless Albacore.windows?
end

Expand Down

0 comments on commit d0e5b0b

Please sign in to comment.